实体框架加载一些,无或所有导航属性动态
查看此 documentation> documentation 我可以看到您可以使用以下语法加载多个导航实体:
using (var context = new DbContext())
{
var userDocs = context.UserDocuments
.Include(userDoc => userDoc.Role.User)
.ToList();
}
这将为我提供角色
和user
导航属性挂在我的userDocument
对象上,但是如果我是否要使用Inclubel的字符串过载,我如何构建要处理多个的代码?
这是行不通的:
return await ctx.UserDocuments.Where(x => x.UserId == userId)
.Include("Role.User").ToList();
我试图这样做,因为我的方法可能会根据调用代码返回一些,全部或没有导航属性。我的目的是将字符串数组添加到存储库方法中,该数组将相应地构建任何必需的导航属性。如果这是错误的方法,是否有人提出了另一项建议,我想知道懒惰负载是否会更优雅的解决方案...?
编辑
这是具有NAV道具的实体:
public partial class UserDocument
{
public int Id { get; set; }
public Guid UserId { get; set; }
public int RoleId { get; set; }
public int AccountId { get; set; }
public virtual Role Role { get; set; } = null!;
public virtual User User { get; set; } = null!;
}
Looking at this documentation I can see that you can load multiple navigation entities using the following syntax:
using (var context = new DbContext())
{
var userDocs = context.UserDocuments
.Include(userDoc => userDoc.Role.User)
.ToList();
}
This will give me Role
and User
navigation properties hung off my UserDocument
object, however if I want to use the string overload of Include, how might I construct the code to handle multiple includes?
This does not work:
return await ctx.UserDocuments.Where(x => x.UserId == userId)
.Include("Role.User").ToList();
I am trying to do it this way as my methods may want some, all or no navigation properties returned depending on the calling code. My intention is to add a string array to the repository method which will build any required navigation properties accordingly. If this is the wrong approach, does anyone have another recommendation, I'm wondering if lazy loading would be a more elegant solution...?
Edit
This is the Entity which has nav props:
public partial class UserDocument
{
public int Id { get; set; }
public Guid UserId { get; set; }
public int RoleId { get; set; }
public int AccountId { get; set; }
public virtual Role Role { get; set; } = null!;
public virtual User User { get; set; } = null!;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你正在寻找这样的东西:
I think you are looking for something like this:
如果您使用
include(String)
方法,则无需包含lambda即可指定属性路径。而不是做
.include(x =>“ cole.user”)
,尝试.include(“ prole.user”)
If you're using the
Include(String)
method, you don't need to include the lambda to specify the property path.Instead of doing
.Include(x => "Role.User")
, try.Include("Role.User")
首先你必须告诉我们什么是“Role.User”?
如果我们不确切知道您写的内容,我们无法回答您。
所以,现在我们知道有两个不同的实体,您可以执行此操作,
我希望这对您有所帮助。 :)
First of all, you must told us what is "Role.User"?
We cannot answer you if we don't know excactly what you wrote.
So, now we are know that are two differents entities you can do this one
I hope this one helps you. :)