Dan*_*mov 2 c# linq-to-entities many-to-many entity-framework entity-framework-4
有一个多对多的UserFeed表位于User和之间Feed,表示类似Twitter的关系.
它只有两个字段,形成一个复合键:UserID和FeedID.
我需要编写一个方法,根据布尔标志从订阅源订阅或取消订阅用户.
public void SetSubscriptionFlag (int userId, int storeId, bool subscribe)
{
}
Run Code Online (Sandbox Code Playgroud)
我是Entity Framework的新手,所以我试图找到并遵循"EF-ish"方式来实现这一目标.
我最初的想法是:
UserFeed我应该创建一个多对多的Subscriptions属性(编辑:这里的命中限制),而不是与中产阶级合作;User通过ID 获取一个实例,检查它是否Feed在其中给出Subscriptions并根据标志和当前存在添加/删除它;相关的代码片段和对我的观点的评论非常感谢.
谢谢!
你可以使用虚拟对象 - 它肯定适用于插入,我希望它也可以用于删除:
建立新关系:
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();
Run Code Online (Sandbox Code Playgroud)
删除现有关系:
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();
Run Code Online (Sandbox Code Playgroud)