删除多对多关系(当您只有实体ID时)

时间:2016-02-07 14:05:55

标签: c# entity-framework many-to-many

我试图从主题中删除用户(多对多关系),但它说,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; }

1 个答案:

答案 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);