【发布时间】:2011-06-30 10:33:47
【问题描述】:
我有两个这样的多对多关系表:
用户(电子邮件地址,姓名)
UserAlerts(emailaddress, AlertId)
警报(AlertId,标题)
警报已添加到数据库中。插入新用户时,我正在查找AlertRepository。问题是,它不仅在 User 和 UsertAlerts 表中创建记录,还添加了额外的 Alert 记录。
我正在使用以下代码:
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();
【问题讨论】:
标签: asp.net entity-framework many-to-many repository-pattern