views:

40

answers:

1

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 inherits 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!

+2  A: 

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.

RPM1984
if i try this: var allContacts = ctx.Users.OfType<Contact>;, I get this error on allContacts: cannot assign method group to implicitly-typed local variable
TheGeekYouNeed
My bad - you need the () at the end. `ctx.Users.OfType<Contact>()`. That will be an IQueryable, if you want a list, do this: `ctx.Users.OfType<Contact>().ToList();`
RPM1984