gpt4 book ai didi

c# - 强制 EF ApplicationUser 加载导航属性

转载 作者:太空狗 更新时间:2023-10-29 23:13:50 24 4
gpt4 key购买 nike

我正在使用 EF6/.Net 4.5.1 在 Web 窗体的用户控件中检索 ListView 的数据。我修改了 ApplicationUser 以包含一个使用 FK 属性的导航属性 [1:1],该属性一直运行良好。

public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreateDate = DateTime.Now;
:\\ deleted stuff
}

public int TaxID { get; set; }
public System.Guid ApplicationId { get; set; }
:\\ deleted stuff

[ForeignKey("TaxID")]
public virtual Personnel Personnel { get; set; }
}

模型已迁移并测试了存储和检索。

完整回发一切正常。

不过,我在网页上添加了一个按钮,用于打开和关闭一个 div,该 div 包含负责创建新成员的 UserControl。 UserControl 抛出一个由容器使用的事件。 Container 然后关闭包含 UC 的 div,用 Listview 重新打开 div,调用 Listview DataBind(),后者调用 GetAllUsers()。

代码:

public IQueryable<ApplicationUser> GetAllUsers()
{
var manager = HttpContext.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
var users = manager.Users.OrderBy(c => c.TaxID);

return users;
}

UserControl 将控制权返回给 Container 后出现问题。

第一个检索 - 总是有一个没有加载 Navigation 属性的 ApplicationUser。这意味着 ListView 中永远不会填充某些字段。

然而,随后的检索(刷新页面或调用行的编辑)似乎会触发导航属性出现。

Image Showing First and Second Retrieve

  1. 如何强制 EF 包含导航属性。语法 manager.Users.Include() 在此上下文中不存在。

  2. 只有列为 ApplicationUser 的动态代理的实体似乎具有导航属性。所以我很困惑为什么初始检索从来都不是动态代理。

  3. ListView 的 Datapager 需要一个 IQueryable 来实现它的分页。我不调用 .ToList() 因为 Datapager 知道什么时候到 这一直工作得很好......一旦有一个完整的页面刷新。为什么需要刷新页面才能实现导航属性?

任何帮助...提前致谢...

最佳答案

添加

using System.Data.Entity;

然后你可以使用Include:

var users = manager.Users.Include(x=> x.Personnel).OrderBy(c => c.TaxID);

如果您想在任何地方包含导航,请在 IdentityConfig.cs 文件中覆盖 ApplicationUserManager.Users,如下所示:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
public override IQueryable<ApplicationUser> Users
{
get
{
return base.Users.Include(x=>x.Personnel);//include what you want here
}
}
//Rest of the original code
}

关于c# - 强制 EF ApplicationUser 加载导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com