强制EF ApplicationUser加载导航属性

Ren*_*hai 5 c# asp.net entity-framework webforms asp.net-identity

我正在使用EF6/.Net 4.5.1在webform上的usercontrol中检索列表视图的数据.我已经修改了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; }
}
Run Code Online (Sandbox Code Playgroud)

该模型已迁移并进行了存储和检索测试.

完整的回发一切正常.

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

代码:

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

    return users;
}
Run Code Online (Sandbox Code Playgroud)

UserControl将控件返回到Container后出现问题.

第一个检索 - 总是有一个ApplicationUser,它没有加载Navigation属性.这意味着列表视图中永远不会填充某些字段.

但是,后续检索(刷新页面或调用行的编辑)似乎会触发导航属性.

显示第一和第二检索的图象

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

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

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

任何帮助......在此先感谢...

Tah*_*ooy 5

using System.Data.Entity;
Run Code Online (Sandbox Code Playgroud)

然后你可以使用Include:

var users = manager.Users.Include(x=> x.Personnel).OrderBy(c => c.TaxID);
Run Code Online (Sandbox Code Playgroud)

如果你想在任何地方包含导航,那么在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
}
Run Code Online (Sandbox Code Playgroud)