Wednesday, April 6, 2011

Entity Framework: Model doesn't reflect DB

I'm probably thinking about this all wrong but I have the following db tables:

alt text

When I run the EF Wizard in VS2008 I get the following model:

alt text

You'll notice that in the EF model shows that the Entity has no field for EntityTypeID or EntityStatusId. Instead it shows it as a navigation property, so the field appears to not be addressable when I instantiate an Entity (pardon the terminology confusion: Entity is a Table/Class in my name space not in the EF namespace). How can I assign an EntityTypeID and StatusTypeID when instantiating an Entity?

From stackoverflow
  • Yes, the entity framework hides foreign key ID properties and shows navigation properties instead. There is a lengthy discussion about why it does that, here. The usual means of assigning a reference to another entity is to assign the entity instance, rather than the foreign key ID value, like this:

    var foo = new Entity();
    var status = (from .... select ...).FirstOrDefault();
    foo.StatusCodes = status;
    

    However, it is possible to assign a foreign key ID directly, if you happen to know what it is:

    foo.StatusCodesReference = new EntityKey(
       "MyEntityContextName.StatusCodesEntitySetName", "StatusCodeId", value);
    

    Obviously, substitute the real values in the above.

    : OK I get it, I tried it in my code and it works. I need a serious reorientation from Linq to SQL -> Linq to Entities. Thanks for your help (again) :-)

0 comments:

Post a Comment