实体框架:多对多关系 [英] Entity Framework: Many to Many Relationship

查看:151
本文介绍了实体框架:多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张表与多对多关系如下:

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

用户(电子邮件地址,名称)

UserAlerts( emailaddress AlertId

UserAlerts(emailaddress, AlertId)

提醒( AlertId ,标题)

警报已经添加到数据库中。当插入新用户时,我正在对 AlertRepository 进行查找。问题是,除了仅在用户 UsertAlerts 表中创建记录之外,它还添加了一个额外的警报记录。

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.

我使用以下代码:

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


推荐答案

为什么不尝试搜索一下你问一个问题?这个问题每个星期被问好几次。在你以前的问题中,我说你应该使用相同的上下文来加载 Alert 并存储 User 。你没有这样做,整个情况复杂。

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:


  • 在这两个仓库中使用相同的上下文,不要分离警报。由于加载警报,上下文将知道它们的存在,并且不会再插入它们。

  • 如果不使用相同的上下文进行加载,则必须附加 Alert 到新的上下文,然后再将它添加到 User 。当您将EF代码包装到存储库时,这很难做。

  • 如果不使用相同的上下文,并且不附加 Alert 到新的上下文,然后再将它添加到用户,您必须修改添加方法用户,并且在上下文中添加 User 之后,您必须迭代每个警报,并将其状态更改为不变

  • 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.

这篇关于实体框架:多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆