实体框架很多 - >许多没有加载

时间:2018-04-10 23:57:37

标签: c# .net entity-framework

我有这样的情况:

Entity User
ICollection<UserPrincipal> UserPrincipals {get;set}

Entity UserPrincipal
UserId int (fk -> User.Id)
PrincipalId int (fk -> User.Id)

所以主要对象是User,有一组UserPrincipal对象,它们只说明哪些用户是该用户的孩子。

当我访问UserObject时,正确填充了UserPrincipals。 UserPrincipal.UserId和UserPrincipal.PrincipalId正确加载并且UserPrincipal.User是用户本身被填充,但是PrincipalUser正在获取一个对象处置错误。

我得到这样的原始用户:

        using (xxxServiceContext context = new xxxServiceContext())
        {
            retVal = context.xxxUsers.Include("UserProducts").Include("UserPrincipals").FirstOrDefault(o => o.UserName == userName && o.IsActive);
        }

所以基本上,我需要做的似乎是在UserPrincipals中包含M-M关系的另一面......如何让PrincipalUser加载PrincipalId用户?

编辑: 用户看起来像:

    public int Id { get; set; }
    public virtual ICollection<UserPrincipal> UserPrincipals { get; set; }

UserPrincipal看起来像:

    public int Id { get; set; }
    public int UserId { get; set; }
    public int PrincipalId { get; set; }
    public virtual User User { get; set; }
    public virtual User PrincipalUser { get; set; }

在我的测试表中,UserPrincipals表有例如1.2。

所以主要User对象是Id = 1。 UserPrincipals有1项。 UserPrincipal.UserId = 1,UserPrincipal.PrincipalUserId = 2。 UserPrincipal.User指向用户1.到目前为止一切顺利。 PrincipalUser具有:ObjectContext实例已被释放,不能再用于需要连接的操作。

我尝试将ForeignKey属性放在UserPrincipal.User和UserPrincipal.PrincipalUser上。同样的事情。

还尝试将UserPrincipal更改为:

    [InverseProperty("User")]
    public virtual ICollection<UserPrincipal> UserPrincipals { get; set; }
    [InverseProperty("PrincipalUser")]
    public virtual ICollection<UserPrincipal> UserPrincipals2 { get; set; }

UserPrincipals2永远不会被填充,并且对象上下文仍然处理错误。

我的EF是ObjectContext,我没有OnModelCreating。我不确定如何在这种情况下建立流利。

0 个答案:

没有答案