2016-07-19 53 views
1

我有两个型号。 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和几个ProfileView一个Viewee

我跑我的所有用户foreach,他们都不具有任何ProfilesViewed如果我查询他们从UsersInclude。我只能从ProfileViews表中检索ProfileViews ...

任何人都有任何想法如何解决这个问题?

+0

更重要的是,ApplicationUser的PK是什么?这种关系的映射是什么? – DevilSuichiro

回答

1

既然你没有提到的ProfileView.Viewer是如何与ApplicationUser.ProfileViewed EF认为他们是不相关的(如果你检查你的数据库,你可以看到另一个FK在ProfileView创造了ApplicationUser.ProfileViewed集合)。因此,将实例添加到ProfileView不会影响User.ProfilesViewed

这个代码添加到Context类,指定每个ApplicationUser通过ProfilesViewed收集有关许多ProfileView

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<ProfileView>().HasRequired(x => x.Viewer) 
       .WithMany(x => x.ProfilesViewed); 
} 
+0

你摇滚,它的工作!每当我创建具有虚拟属性的模型时,EF都会自动理解这种关系。我想这对于做出假设有点太不寻常了。 – aBertrand

0

的关系可能需要进行解释,以正确创建。我认为这是错误的,因为您有两个从ProfileView到ApplicationUser的关系。请参阅如何配置使用EF代码第一次非常规的关系细节this MSDN article“组态非常规的外键名称”。