简体   繁体   English

如何在实体框架中添加或删除多对多关系?

[英]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.UserFeed之间有一个多对多的UserFeed表,表示类似 twitter 的关注关系。
It only has two fields, which form a composite key: UserID and FeedID .它只有两个字段,形成一个复合键: UserIDFeedID

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:我最初的想法是:

  • Instead of working with the middle UserFeed class, I should create a many-to-many Subscriptions property ( EDIT: hit limitations here);而不是使用中间的UserFeed class,我应该创建一个多对多的Subscriptions属性(编辑:点击这里的限制);
  • After I've done so, I'll need to fetch a 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 ,并根据标志和当前存在添加/删除它;
  • Figure out how to avoid racing conflicts when there is a time interval before the check and adding/deleting and user manages to submit two adding or deletion requests;当在检查和添加/删除之前有一个时间间隔并且用户设法提交两个添加或删除请求时,弄清楚如何避免赛车冲突;
  • Optimize my code as to avoid unneccessary SELECTs, if any occur, because all I really want to do is a single SELECT and single INSERT/DELETE.优化我的代码以避免不必要的选择(如果有的话),因为我真正想做的只是一个 SELECT 和一个 INSERT/DELETE。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM