Entity Framework inheritance from SQL Membership
I am using Entity Framework 3.5. I have created开发者_开发问答 an object that calls "Persons" that is inherited from SQL Membership table (aspnet_Users), they are linked by UserId (Guid) with 1-to-(0..1) relationship and they both belong to "UserSet".
Say, I have an existing "aspnet_User" called "jsmith" in the membership database already. How can I create just the "Person" (child) that links it to "jsmith" in entity framework?
Guid guid = new Guid("xxxx-xxxx-xxx..") // jsmith Guid
User user = GetUserByGuid(guid); // Assuming a function gets "jsmith" as "User"
// Try 1:
Person person = new Person();
person.UserId = guid;
context.AddToUserSet(person);
context.SaveChanges(); // This doesn't work and throws an error
// Try 2:
Person.CreatePerson(person); // Doesn't work either, because it creates a whole new user
context.SaveChanges(); // Throws an error
I even tried to create an EntityKey and use detach/attach, didn't work either. Am I doing anything wrong? Any help is appreciated.
R.B.
You should not put SQL membership into your entity model. ASP.NET membership is intended to be pluggable; you can swap out the SQL membership provider for, say, an OpenID or domain authentication provider. Mapping the SQL membership tables makes you totally dependent on the specific implementation of one version of that provider, which is bad coupling.
Also, even if you did do this, inheritance is the wrong relationship. A user has an account. A user is not an account. So the correct relationship is composition, not inheritance.
Perhaps "Person" is the wrong relationship in the example. However, if you are talking about extending ASP.NET memembership by adding more properties like "FirstName", "LastName", etc.. this is not totally wrong. There are some articles talk about extending SQL membership and/or creating "Custom Membership" by adding your own db table and then inherited from base MembershipUser class. In that case, it is inheritance.
There are some articles that talks about extending membership, but not on Entity though: http://www.code-magazine.com/Article.aspx?quickid=0703071
More articles
- codesmart.wordpress.com/2009/03/27/extending-the-microsoft-aspnet-membership-provider/
Also, you may want to consider using Profiles as alternative.
精彩评论