Thursday, April 21, 2011

Assign value to column with reference, using entity framework

Hello

I have a problem assigning a value to an entity that has a reference. I get the intellisense and all but I get a null-reference exception when I try to assign it to the object passed into the function that saves to database.

        public ActionResult BookingViewEdit([Bind(Include = "BookingViewID,Enabled,ObjectLimit,RSSenabled")]BookingView bv, int selCustomers)
    {
        bv.Customers.CustomerID = selCustomers;

        _bvs.SaveBookingView(bv);

Whats needed to do to assign the value for CustomerID? the FK-key is in the "BookingView"-table, and if I just hit "bv." there is no CustomerID there.

Thanks in advance

/M

From stackoverflow
  • Is "Customers" actually a single Customer, not a list?

    In that case, you could do something like:

    bv.CustomerReference.EntityKey = new EntityKey("MyEntities.Customers", "CustomerId", selCustomers);
    

    Obviously, replace "MyEntities.Customers" with the actual entity context and entity set names.

    I'll add that it's extremely confusing to use plural argument/property names for single objects.

    molgan : In my entity-diagram there are no plurals. So the class there is called Customer
    Craig Stuntz : The class should be Customer (as you have it). The entity set name should be Customers. The selCustomers argument should be selCustomer (or, better per FxCop rules, selectedCustomer). bv.Customers should be bv.Customer

0 comments:

Post a Comment