我对初始化集合类型的导航属性感到困惑。在我在网上看到的示例中,属性总是在类构造函数中显式初始化,但是在我的项目中,我有两组这样的属性,一组没有这样的初始化,一组没有:
public class User
{
public int UserId { get; set; }
[System.ComponentModel.DataAnnotations.Schema.InverseProperty("Requested")]
public virtual System.Collections.Generic.ICollection<Friendship> RequestedFriendships { get; set; }
[System.ComponentModel.DataAnnotations.Schema.InverseProperty("Received")]
public virtual System.Collections.Generic.ICollection<Message> ReceivedMessages { get; set; }
}
public class Message
{
public int MessageId { get; set; }
string Message { get; set; }
public virtual System.Collections.Generic.ICollection<User> Received { get; set; }
}
public class Friendship
{
public int FriendshipId { get; set; }
public int RequestedUserId { get; set; }
public virtual User Requested { get; set; }
}
以下作品:
db.Users.Single(u => u.UserId == userId).RequestedFriendships.Add(new B.Models.Friendship
{
RequestedUserId = userId,
});
还有这个:
B.Models.Message message = db.Messages.Add(new B.Models.Message
{
Message = text
});
db.SaveChanges();
但是,按照上述情况,以下失败:
message.Received.Add(db.Users.Single(u => u.UserId == userId));
既然message.Received
是null
上面。这里和第一个成功的有什么区别?