Entity Framework code first aspnet_Users mapping /

2019-02-28 20:13发布

问题:

I was wondering with Entity Framework 4.1 code first how do you guys handle queries that involve an existing aspnet_Users table?

Basically I have a requirement for a query that involves the aspnet_Users so that I can return the username:

SELECT t.Prop1, u.Username
FROM Table1 t 
INNER JOIN aspnet_User u ON t.UserId = u.UserId
Where t.Prop2 = true

Ideally in linq I would like:

from t in context.Table1
join u in context.aspnet_Users on t.UserId equals u.UserId
where t.Prop2 = true

But I'm not sure how to get aspnet_Users mapping to a class User? how do I make aspnet_Users part of my dbset ?

Any help would be appreciated, thanks in advance

回答1:

Don't map aspnet_Users table or any other table related to aspnet. These tables have their own data access and their own logic for accessing. Mapping these tables will introduce code duplication, possible problems and breaks separation of concerns. If you need users for queries, create view with only needed information like id, user name, email and map the view. The point is that view will be read only, it will contain only allowed data and your application will not accidentally modify these data without using ASP.NET API.



回答2:

First read Ladislav's answer. If you still want to go ahead : to do what you want would involve mapping the users and roles and members tables into the codefirst domain - which means writing a membership provider in code-first.

Luckily there is a project for that http://codefirstmembership.codeplex.com/ although its not a perfect implementation. The original is VB, look in the Discussion tab for my work on getting it running in c# MVC.

I'm working with the author on a better implementation that protects the membership data (password, last logged on date, all of the non-allowed data) but allow you to map and extend the user table. But its not ready yet!



回答3:

You don't really need to use Entity Framework to access aspnet_membership provider accounts. You really just need to create an instance of the membership object, pass in a unique user identifier and a Boolean value indicating whether to update the LastActivityDate value for the user and the method returns a MembershipUser object populated with current values from the data source for the specified user.

You can then access the username by using the property of "Username".

Example:

private MembershipUser user = 
    Membership.GetUser(7578ec40-9e91-4458-b3d6-0a69dee82c6e, True);

Response.Write(user.UserName);

In case you have additional questions about MembershipProvider, you can read up on it on the MSDN website under the title of "Managing Users by Using Membership".

Hope this helps you some with your requirement.