实体框架关系破裂

时间:2016-07-19 10:04:51

标签: c# entity-framework

我有两个型号。 ApplicationUser

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public DateTime AccountCreationDate { get; set; }

    public virtual ICollection<ProfileView> ProfilesViewed { get; set; }
}

ProfileView

public class ProfileView
{
    public int Id { get; set; }

    public DateTime ViewDate { get; set; }

    public virtual ApplicationUser Viewer { get; set; }

    public virtual ApplicationUser Viewee { get; set; }

}

实体框架似乎正确地创建了我的表。我可以执行以下操作并检索用户的ProfileViews

db.ProfileViews.Where(p => p.Viewer.Id == currentUser.Id);

我的问题是我似乎无法做到以下几点:

db.Users
    .Where(u => u.Id == currentUser.Id)
    .Include(u => u.ProfilesViewed);

上述内容会为该用户返回null,即使它在Viewer上是VieweeProfileView

我在所有用户上都运行了foreach,如果我使用ProfilesViewedUsers表中查询,则他们似乎都没有Include。我只能从ProfileViews表中检索ProfileViews ...

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

由于您未提及ProfileView.ViewerApplicationUser.ProfileViewed EF的关系如何认为它们不相关(如果您检查数据库,则可以看到在ProfileView中创建的另一个FK对于ApplicationUser.ProfileViewed集合)。因此,向ProfileView添加实例不会影响User.ProfilesViewed

将此代码添加到Context课程,以指定每个 ApplicationUser很多 ProfileView到{{ 1}}集合。

ProfilesViewed

答案 1 :(得分:0)

可能需要解释关系才能正确创建。我认为这是错误的,因为你有两个从ProfileView到ApplicationUser的关系。请参阅&#34;配置非常规外键名称&#34;在this MSDN article中有关如何使用EF Code First配置非常规关系的详细信息。