我在以下类之间有两个一对多的关系
public class SiteMember
{
public int SiteMemberID { get; set; }
public virtual List<FriendshipInvitation> InvitationsSent { get; set; }
public virtual List<FriendshipInvitation> InvitationsReceived { get; set; }
}
public class FriendshipInvitation
{
public int InvitingUserID { get; set; }
public SiteMember InvitingUser { get; set; }
public int InvitedUserID { get; set; }
public SiteMember InvitedUser{ get; set; }
}
然后在控制器中,我有以下代码(从数据库加载一个 SiteMember):
SiteMember sm = repoSiteMember.GetUserByName(User.Identity.Name);
在此刻
sm.InvitationsReceived.InvitingUserId = 1;
sm.InvitationsReceived.InvitingUser = null
然后我有以下行(从 db 加载所有 SiteMembers):
IEnumerable<SiteMember> all = repoSiteMember.GetAll();
之后
sm.InvitationsReceived.InvitingUserId = 1
sm.InvitationsReceived.InvitingUser = proxy to SiteMember object.
我的问题是:这是正常行为吗?我很确定我可以用 include 语句“修复”空指针,但我发现从 db 加载所有元素实际上改变了对象的状态很奇怪。(空 => 代理)。代理应该从一开始就在那里吗?
编辑: 确认一下,include 语句确实解决了空引用的问题,但这不是这里的问题。
DataContext.Members
.Include("InvitationsSent.InvitedUser")
.Include("InvitationsReceived.InvitingUser")
.FirstOrDefault(e => e.UserName == userName);
Edit2:现在包括方法。
public SiteMember GetUserByName(string userName)
{
return base.DataContext.Members.FirstOrDefault(e => e.UserName == userName);
}
public IEnumerable<SiteMember> GetAll()
{
return base.DataContext.Members.ToList();
}
Edit3:您可能需要它来重新创建模型。
modelBuilder.Entity<FriendshipInvitation>()
.HasRequired(e => e.InvitedUser)
.WithMany(e => e.InvitationsReceived)
.HasForeignKey(e => e.InvitedUserID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<FriendshipInvitation>()
.HasRequired(e => e.InvitingUser)
.WithMany(e => e.InvitationsSent)
.HasForeignKey(e => e.InvitingUserID);
modelBuilder.Entity<FriendshipInvitation>()
.HasKey(e => new { e.InvitingUserID, e.InvitedUserID, e.InvitationNo });