【发布时间】:2017-09-22 07:30:12
【问题描述】:
我使用默认的 ASP.NET MVC 5 用户身份在我的数据库中存储和管理用户。
我还有其他将引用用户表的数据库表。
我面临的问题是如何在查询具有外键(userid)的某个表时提取用户详细信息。
根据我在网上看到的情况,我无法直接查询 users 表(“不是最佳实践”)。
所以我必须使用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,因此上述方法不起作用。
有没有办法解决这个问题?
【问题讨论】:
-
如果您使用
HodUserId对其主表进行FK 引用,则直接在查询中引用users表没有问题。 -
@sajal,用户表不是我的 dbcontext 的一部分。那么是不是就像在 dbcontext 中添加一个 dbset 一样简单。还是我需要编写其他代码?
标签: asp.net-mvc linq asp.net-identity