我有以下模型:
public class Transfer
{
public Article Article { get; set; }
public Branch BranchFrom { get; set; }
public Branch BranchTo { get; set; }
public User User { get; set; }
}
public class Article
{
public int Id{ get; set; }
public string Description { get; set; }
}
public class Branch
{
public int Id { get; set; }
public string Address { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
我需要获取特定用户进行的所有转移的列表,并加载其所有相关实体(BranchFrom,BranchTo,Article,User)。
在EF 6中,我可以使用以下代码轻松做到这一点:
_dbContext.Transfer.Include(x=>x.BranchFrom).Include(x=>x.BranchTo).Include(x=>x.Article).Include(x=>x.User).Where(x=>x.User.Id == userId).ToListAsync();
鉴于在EF Core 2.1中必须定义联接表,因此我将它们添加如下:
public class TransferUser
{
public int TransferId { get; set; }
public int UserId { get; set; }
public Transfer Transfer { get; set; }
public User User { get; set; }
}
public class TransferArticle
{
public int TransferId { get; set; }
public int ArticleId { get; set; }
public Transfer Transfer { get; set; }
public Article Article { get; set; }
}
public class TransferBranchFrom
{
public int TransferId { get; set; }
public int BranchId { get; set; }
public Transfer Transfer { get; set; }
public Branch Branch { get; set; }
}
public class TransferBranchTo
{
public int TransferId { get; set; }
public int BranchId { get; set; }
public Transfer Transfer { get; set; }
public Branch Branch { get; set; }
}
因此,我将Transfer模型修改为:
public class Transfer
{
public TransferArticle TransferArticle { get; set; }
public TransferBranch TransferBranchFrom { get; set; }
public TransferBranch TransferBranchTo { get; set; }
public TransferUser TransferUser { get; set; }
}
现在我不知道查询的方式。
我这样做是可行的,但是只加载传输和用户
_dbContext.Transfer.Include(x=>x.TransferUser).Where(x=>x.TransferUser.UserId == userId).ToListAsync();
当我添加另一个表时,它不起作用并引发异常:
_dbContext.Transfer.Include(x=>x.TransferUser).Include(x=>x.TransferBranchFrom).Where(x=>x.TransferUser.UserId == userId).ToListAsync();
在这种情况下,我找不到任何有关如何加载所有实体的示例