How do I query Entity Framework for a user in aspnet_Users?
I have added the SqlRoleProvider tables aspnet_Users, aspnet_Roles, and aspnet_UsersInRoles to my Entity Framework 1.0 model in VS 2008.
I've tried the following which intellisense won't even help me with.
private void BindFormView(string userName)
{
using (var context = new MyEntities())
{
var users = from u in context.aspnet_Users
where u.UserName = userName
select u;
}
//...
}
My eventual goal is to get all of the roles a given user has. It's all looks right in my model, but I cannot seem to access it effec开发者_开发百科tively.
Dude, do not map the membership tables.
Access them via the Membership Provider API:
Membership.GetUser("blah");
Why shouldn't you map it?
- Because it's presuming SQL (defeats the point of a "model" abstraction in EF)
- Kidding yourself if you can figure out the complex relationships/associations in the database
The Membership API has all the information you require.
To get the roles for a user, use RoleProvider.GetRolesForUser
It looks like the roles are setup as a navigation property from the users. So, building on your code you should be able to do something like this:
private void BindFormView(string userName)
{
using (var context = new MyEntities())
{
//Get the first user matching your query
var user = (from u in context.aspnet_Users
where u.UserName == userName
select u).FirstOrDefault();
//Using the navigation properties, get the roles associated with this user
var roles = user.aspnet_Roles().ToList();
}
//...
}
精彩评论