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

Removing a many-to-many relationship (when you have only the entity ids)

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

您的导航属性(在本例中为 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);