[英]Entity Framework: Many to Many Relationship
I have two tables with a Many-To-Many relationship like this:我有两个具有多对多关系的表,如下所示:
User( emailaddress , Name)用户(电子邮件地址,姓名)
UserAlerts( emailaddress , AlertId ) UserAlerts(电子邮件地址,AlertId )
Alert( AlertId ,Title)警报(警报ID ,标题)
Alerts have already been added to the database.警报已添加到数据库中。 When inserting a new user, I am doing a lookup on the
AlertRepository
.插入新用户时,我正在查找
AlertRepository
。 The problem is, Instead of creating a record in the User and the UsertAlerts tables only, its also adding an extra Alert record.问题是,它不仅在User和UsertAlerts表中创建记录,还添加了额外的警报记录。
I am using the following code:我正在使用以下代码:
public ActionResult Register(UserModel model, int[] Alerts)
User user = new MidTier.Models.User();
user.Name = model.Name;
user.EmailAddress = model.EmailAddress;
if (Alerts!=null)
{
IRepository<Alert> alertRepository = new AlertRepository();
foreach (int alertId in Alerts)
{
Alert alert = alertRepository.First(a=>a.ID== alertId);
alertRepository.Detach(alert);
if (alert != null)
{
alert.Enabled = true;
user.Alerts.Add(alert);
}
}
}
userRepository.Attach(user);
userRepository.Add(user);
userRepository.Save();
Why don't you try to search little bit before you ask a question?为什么不在你问问题之前尝试搜索一下? This problem is asked several times per week.
这个问题每周被问好几次。 In your previous question I said you that you should use same context for loading
Alert
and storing User
.在您之前的问题中,我说过您应该使用相同的上下文来加载
Alert
和存储User
。 You didn't do it and complicated whole situation.你没有这样做,使整个情况复杂化。
The context doesn't know anything about existence of the alert.上下文对警报的存在一无所知。 Once you call
Add
for user it will add all entities which are not tracked yet.一旦您为用户调用
Add
,它将添加尚未跟踪的所有实体。 There are three ways to solve this:有三种方法可以解决这个问题:
Alert
to the new context before you add it to User
.Alert
附加到新上下文,然后再将其添加到User
。 That is hard to do when you wrap EF code to repositories.Alert
to the new context before you add it to User
you must modify your Add
method for User
and after adding User
to the context you must iterate every alert and change its state to Unchanged
.Alert
添加到User
之前不会将其附加到新上下文,则必须修改User
的Add
方法,并且在将User
添加到上下文后,您必须迭代每个警报并将其 state 更改为Unchanged
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.