开发者

How do I get data from entities that inherit others in Entity Framework 4.0

开发者 https://www.devze.com 2023-01-20 22:17 出处:网络
new to EF - please bear with me. Due to the way the database was designed, in my model I have a User entity.The Contact entity inherits from the user entity, and the Profile entity 开发者_如何学Cinhe

new to EF - please bear with me.

Due to the way the database was designed, in my model I have a User entity. The Contact entity inherits from the user entity, and the Profile entity 开发者_如何学Cinherits from the Contact entity.

How can I get a list of Profiles, and, how do I create a Profile?

I am able to get a list of Users no problem.

Your help is greatly appreciated!


For Entity Framework 4 Table-Per-Type Inheritance, you need 2 things:

  1. A "parent" table, and a "child" table. The "child" table should have a FK to the "parent" table's PK.
  2. You need to setup an inheritance association in the EDM. If done correctly, you should see a arrowhead association between the entities, and the child table should have text in the name stating it's parent.

Now, you can get "Users" this way: (i assume you are already doing this)

var allUsers = ctx.Users;

Now getting "Contacts" is special - because it belongs to the "Users" entity set (you can prove this by looking at the properties for the "Contacts" entity).

This is how you get Contacts:

var allContacts = ctx.Users.OfType<Contact>();

How does that work? Well OfType is an IEnumerable extension method which filters all the elements based on a given type. So it's basically a foreach loop:

foreach (var item in source)
{
   if (item is Contact) result.Add(item);
}

Similarily, this is how you get Profiles:

var allProfiles = ctx.Users.OfType<Profile>();

To add a new Profile, again - add it to the "Users" entity set:

var newProfile = new Profile { Name = "Foo" };
ctx.Users.AddObject(newProfile);

On a side note, i hope these tables are not relating to the ASP.NET Membership schema. If they are, stop right now. You should not map these tables via EF. Access the functionality via the regular Membership API.

HTH.

0

精彩评论

暂无评论...
验证码 换一张
取 消