如何使用linq加入aspnet_membership和aspnet_users?

时间:2013-01-25 05:50:18

标签: c# linq join

我很难弄清楚如何使用LINQ加入aspnet表。 所以这是我的询问。

  

如何使用LINQ / MVC加入这些aspnet表或如何获取这些aspnet表的确切列名或数据.aspnet_Membership,aspnet_Users,aspnet_UsersInRoles和aspnet_Roles。

获取值或列名后,我将在不同数据库的另外两个表中加入它们。

这是我在sqlserver中的代码,我想将其转换为LINQ语句。

SELECT AU.UserId,
       AU.UserName,
       ( MNTP.LastName + ',' + MNTP.FirstName + ' '
         + LEFT(MNTP.MiddleName, 1) + '.' ) Name,
       AR.RoleName
FROM   aspnetdb..aspnet_Membership AM
       INNER JOIN aspnetdb..aspnet_Users AU
               ON AM.UserId = AU.UserId
       INNER JOIN aspnetdb..aspnet_UsersInRoles AUR
               ON AU.UserId = AUR.UserId
       INNER JOIN aspnetdb..aspnet_Roles AR
               ON AUR.RoleId = AR.RoleId
       INNER JOIN User_ManagementDB..MNT_Users MNTU
               ON AU.UserId = MNTU.aspnet_UsersID
       INNER JOIN User_ManagementDB..MNT_Person MNTP
               ON MNTU.PersonID = MNTP.ID 

这是我尝试将其转换为LINQ语句的代码:

var _rolesRepo = new RolesRepository();
var _users = LoadAll();// Um_MNT_Users
var _person = entities.People.ToList();// UM_Person
var _role = _rolesRepo.LoadAll(); 

var _userMem = Membership.GetAllUsers()
        .Cast<MembershipUser>()
        .Select(m => m).ToList(); // I dont know if this is the right syntax to get the aspnet_membership.

var _query = from user in _users
             join personID in _person on user.PersonID equals personID.ID 

请帮帮我们。

1 个答案:

答案 0 :(得分:1)

由于我没有看到用Entity Framework标记的问题,我假设您无法使用该逻辑创建存储过程并在需要结果时调用它...

如果您的所有数据都在内存中,则可以使用此查询:

var result = AspMemmership // the collection of data from aspnetdb..aspnet_Membership table
    .Join(AspUsers,        // the collection of data from aspnetdb..aspnet_Users table
        m => m.UserId,
        u => u.UserId,
        (m, u) => u)
    .Join(AspUsersInRoles,
        u => u.UserId,
        ur => ur.UserId,
        (u, ur) => new
        {
            u.UserId,
            u.UserName,
            ur.RoleId
        })
    .Join(AspRoles,
        x => x.RoleId,
        r => r.RoleId,
        (x, r) => new
        {
            x.UserId,
            x.UserName,
            r.RoleName
        })
    .Join(MNT_Users,
        x => x.UserId,
        u => u.aspnet_UsersID,
        (x, u) => new
        {
            x.UserId,
            x.UserName,
            u.PersonId,
            r.RoleName
        })
    .Join(MNT_Persons,
        x => x.PersonId,
        p => p.Id,
        (x, p) => new
        {
            x.UserId,
            x.UserName,
            u.PersonId,
            Name = String.Format("{0},{1} {2}.", 
                p.LastName, p.FirstName, p.MiddleName.Substring(0, 1)),
            r.RoleName
        })