0

我正在使用 MVC3、C#、.NET4、EF5。我正在使用 ASP.NET Membership 提供程序。我为每个用户使用一个角色,尽管该模型支持 1 个用户多个角色。

提取用户信息时,我需要在 LINQ 查询中提取这一角色。本质上,我只需要给定用户的“First()”角色记录。

我有一个 Application User 表,它使用 AspNet.Membership 表映射 1 到 1。

所以像:

List<StdOrgUser> myUsers = Model.Select(i => new StdOrgUser(){
    Id=i.Id,
    Rolename = i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.FirstOrDefault().RoleName
}).ToList();

Intellisense 还允许我编写上面的代码,但实际上它并没有运行。我应该如何获得这个角色名值以及我的用户详细信息以获取此记录?该模型将进入 WebGrid 进行显示。

编辑:

我修改后的代码,pre null 测试建议!

var myUsers = Model.Select(i => new{ 
    Id = i.Id, 
    Firstname = i.Firstname, 
    initials = i.Initials, 
    Lastname = i.Lastname, 
    Username = i.Aspnet_Membership.Aspnet_Users.UserName, 
    RoleName = i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.FirstOrDefault().RoleName, 
        Organisation = i.StdOrg.Name 
}).ToList();

EDIT2:发布空测试:

var myUsers = Model.Select(i => new { 
    Id = i.Id, 
    Firstname = i.Firstname, 
    initials = i.Initials, 
    Lastname = i.Lastname, 
    Username = i.Aspnet_Membership.Aspnet_Users.UserName, 
    RoleName = i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.Any() ? i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.FirstOrDefault().RoleName : "No Roles",
        Organisation = i.StdOrg.Name 
    }).ToList();

然后我将第二个模型输入我的 webgrid。

4

2 回答 2

1

You need to move your access of the RoleName property up the query pipeline a little bit. Currently you're doing this:

i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.FirstOrDefault().RoleName

So if Aspnet_Roles.FirstOrDefault() returns the default (null) you get a null ref exception. Instead, you should project Aspnet_Roles to RoleName first, then use FirstOrDefault():

 i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.Select(ar => ar.RoleName).FirstOrDefault()

If you need to substitute in a default role, you can just coalesce:

 i.Aspnet_Membership.Aspnet_Users.Aspnet_Roles.Select(ar => ar.RoleName).FirstOrDefault() ?? "No Role"

This makes your query less verbose when compared to using Any to check for nulls (and it'll be more efficient on the SQL side, too).

于 2013-08-25T13:22:53.233 回答
0

这样的事情对你有用吗?

var query =
    from i in Model
    from r in i
        .Aspnet_Membership
        .Aspnet_Users
        .Aspnet_Roles
        .Take(1)
    select new StdOrgUser()
    {
        Id = i.Id,
        Rolename = r.RoleName
    };

List<StdOrgUser> myUsers = query.ToList();
于 2013-08-25T05:14:39.660 回答