[英]How to add or remove a many-to-many relationship in Entity Framework?
There's a many-to-many UserFeed
table that stands between User
and Feed
and denotes a twitter-like follow relationship.在User
和Feed
之间有一个多对多的UserFeed
表,表示类似 twitter 的关注关系。
It only has two fields, which form a composite key: UserID
and FeedID
.它只有两个字段,形成一个复合键: UserID
和FeedID
。
I need to write a method that will subscribe or unsubscribe a user from a feed based on a boolean flag.我需要编写一个方法来根据 boolean 标志订阅或取消订阅用户的订阅。
public void SetSubscriptionFlag (int userId, int storeId, bool subscribe)
{
}
I'm new to Entity Framework so I'm trying to find and follow an "EF-ish" way to accomplish this.我是 Entity Framework 的新手,所以我试图找到并遵循“EF-ish”的方式来实现这一点。
My initial thoughts are:我最初的想法是:
UserFeed
class, I should create a many-to-many Subscriptions
property ( EDIT: hit limitations here);而不是使用中间的UserFeed
class,我应该创建一个多对多的Subscriptions
属性(编辑:点击这里的限制);User
instance by ID, check whether it has given Feed
in its Subscriptions
and add/delete it depending on the flag and current existence;完成后,我需要按 ID 获取User
实例,检查它是否在其Subscriptions
中提供了Feed
,并根据标志和当前存在添加/删除它;A relevant code snippet and comment on my points is highly appreciated.高度赞赏相关的代码片段和对我的观点的评论。
Thanks!谢谢!
You can use dummy objects - it definitely works for insert and I hope it can be used for delete as well:您可以使用虚拟对象 - 它绝对适用于插入,我希望它也可以用于删除:
Create new relation:创建新关系:
var user = new User() { Id = userId };
context.Users.Attach(user);
var store = new Store() { Id = storeId };
context.Stores.Attach(store);
// Now context trackes both entities as "existing"
// and you can build a new relation
user.Subscriptions.Add(store);
context.SaveChanges();
Remove existing relation:删除现有关系:
var user = new User() { Id = userId };
var store = new Store() { Id = storeId };
user.Subscriptions.Add(store);
context.Users.Attach(user);
// Now context trackes both entities as "existing"
// with "existing" relation so you can try to remove it
user.Subscriptions.Remove(store);
context.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.