我有两个型号。 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
上是Viewee
和ProfileView
。
我在所有用户上都运行了foreach
,如果我使用ProfilesViewed
从Users
表中查询,则他们似乎都没有Include
。我只能从ProfileViews
表中检索ProfileViews
...
任何人都知道如何解决这个问题?
答案 0 :(得分:1)
由于您未提及ProfileView.Viewer
与ApplicationUser.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配置非常规关系的详细信息。