简体   繁体   English

实体框架:多对多关系

[英]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.问题是,它不仅在UserUsertAlerts表中创建记录,还添加了额外的警报记录。

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:有三种方法可以解决这个问题:

  • Use the same context in both repositories and do not detach alerts.在两个存储库中使用相同的上下文并且不要分离警报。 Because of loading alerts, context will know about their existence and doesn't insert them again.由于加载警报,上下文将知道它们的存在并且不会再次插入它们。
  • If you don't use the same context for loading you must attach the 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.当您将 EF 代码包装到存储库时,这很难做到。
  • If you don't use the same context and you will not attach 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之前不会将其附加到新上下文,则必须修改UserAdd方法,并且在将User添加到上下文后,您必须迭代每个警报并将其 state 更改为Unchanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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