2016-03-24 53 views
0

我遇到了映射Roles屬性的問題,所以它對應於UserViewModelLinq把實體投影到IEnumerable中

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); 

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); 

var users = (from u in userManager.Users 
      join r in roleManager.Roles 
      on u.Id equals r.Id   
      select new UserViewModel { Id = u.Id, Username = u.UserName, Password = u.PasswordHash, Roles = select new Role { Name = r.Name }}); 

public class UserViewModel 
{ 
    public string Id { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public IEnumerable<Role> Roles { get; set; } 
} 

public class Role 
{ 
    public string Name { get; set; } 
} 

我該如何讓Linq實體投影?

回答

0

我覺得你有你的查詢設置它最有可能不會在上班的路上,你需要一個子查詢,因爲你需要返回與列表中的項目/名單我會做類似

由於您使用不同的上下文,你可以嘗試做以下 我會建議你有一些使用語句,所以你會清理你的內存,但你可以轉換它使用列表到實際內存對象,然後過濾內存對象(只要確保您的數據是不要大)

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>().Users.ToList(); 

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())).Roles.ToList(); 


var users = (from u in userManager.Users  
       select new UserViewModel 
       { 
        Id = u.Id, 
        Username = u.UserName, 
        Password = u.PasswordHash, 
        Roles =(from r in roleManager.Roles 
          where r.Id==u.Id 
          select new Role 
          { 
           Name = r.Name 
           }).ToList()); 
+0

試過那種子查詢,但它總是「指定的LINQ表達式包含引用查看與不同上下文相關的查詢。「如在這種情況下。 – netdis

+0

嘗試以上更新 –

+0

現在開始工作,直接在'var userManager'中指定它,從roleManager.Roles'中的'r中移除角色。在當前設置調用ToList是好的。 – netdis