Entity Framework: Many to Many Relationship
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 o开发者_如何学Gon 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();
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 toUser
. 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 toUser
you must modify yourAdd
method forUser
and after addingUser
to the context you must iterate every alert and change its state toUnchanged
.
精彩评论