我试图从主题中删除用户(多对多关系),但它说,topic.Users
为空。我做错了什么?
var user = new User { Id = userId };
var topic = new Topic { Id = topicId };
context.Users.Attach(user);
context.Topics.Attach(topic);
topic.Users.Remove(user);
实体类
主题:
[InverseProperty("TopicsSubscribed")]
public virtual ICollection<User> Users { get; set; }
用户:
public virtual ICollection<Topic> TopicsSubscribed { get; set; }
答案 0 :(得分:2)
您的导航属性(在这种情况下为Users
)未加载,因为您的topic
实体未被动态代理包装,因此导航属性不会延迟加载。
您可以显式加载Users
属性,如下所示:
var user = new User { Id = userId };
var topic = new Topic { Id = topicId };
context.Users.Attach(user);
context.Topics.Attach(topic);
context.Entry(topic).Collection(t => t.Users).Load(); // explicitly load Users ...
topic.Users.Remove(user);