ASP.NET MVC应用程序用户linq加入其他表

问题描述 投票:3回答:2

我使用默认的ASP.NET MVC 5用户身份来存储和管理我的数据库中的用户。

我有其他数据库表将引用users表。

我面临的问题是如何在查询具有外键的某个表(userid)时提取用户详细信息。

从我在网上看到的,我不能直接查询用户表(“不是最佳实践”)。

所以我必须使用ApplicationDbContext来获取用户列表:

var userContext = new ApplicationDbContext();
var db_users = userContext.Users.Select(x => new UserSearchResult() 
{
  ApplicationUserId = x.Id,
  Email = x.Email,
  Username = x.UserName,
  Fullname = x.FullName
});

然后我的linq查询将是例如:

var query = (from dep in Dbcontext.Departments
             from usr in db_users.Where(x => x.ApplicationUserId == dep.HodUserId).DefaultIfEmpty()
             join cat in Dbcontext.Categories on dep.CategoryId equals cat.CategoryId
             select new DepartmentSearchResult() 
             {
               DepartmentId = dep.DepartmentId,
               DepartmentName = dep.DepartmentName,
               HodName = usr.Fullname,
               CategoryName = cat.CategoryName
             });

但是,由于SQL不了解db_users,因此上述操作无效。

有办法解决这个问题吗?

asp.net-mvc linq asp.net-identity
2个回答
3
投票

您可以在使用UserId作为外键的模型中添加User的导航属性。查询该特定项目时包括用户详细信息。

在你的部门模型中说

public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ApplicationUser User { get; set; } //Navigation Property
        public string UserId { get; set; }  //Foreign Key
    }

在任何操作中查询部门信息时

var _context = new ApplicationDbContext();
var department = _context.Departments.Include(c => c.User).FirstOrDefault();

在这里,我使用FirstOrDefault()从db获得单个(首先是准确的)项目。您可以根据自己的要求使用任何适当的方法。

现在在部门中,您只需浏览department.User.FullName或您需要的任何用户属性即可访问用户信息


2
投票

你不应该这样做 - 你可以将你感兴趣的用户具体化到一个集合并加入到它(但是然后连接将在内存中完成),或者你可以将两个表放在一个数据上下文中并执行正常加入。您不应该跨数据上下文连接,因为它们在查询时可能都具有不一致的数据库视图...

© www.soinside.com 2019 - 2024. All rights reserved.