Entity Framework: Many to Many Relationship

人盡茶涼 提交于 2019-12-11 17:44:38

问题


I have two tables with a Many-To-Many relationship like this:

User(emailaddress, Name)

UserAlerts(emailaddress, AlertId)

Alert(AlertId,Title)

Alerts have already been added to the database. When inserting a new user, I am doing a lookup on the AlertRepository. The problem is, Instead of creating a record in the User and the UsertAlerts tables only, its also adding an extra Alert record.

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();

回答1:


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. 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. 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. That is hard to do when you wrap EF code to repositories.
  • 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.


来源:https://stackoverflow.com/questions/6533440/entity-framework-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!