Misha Zaslavsky
Misha Zaslavsky

Reputation: 9712

Add with Many to Many relationship

I am using Entity framework and I have Users, Events and a table UsersEvents. I know to this questions I probably can find on google, and I already tried but somehow, still have problems.

So I have:

User: UserId, Name

Event: EventId, Title

UserEvents: UserId, EventId

I want to create Event.

So on my Repository I have a method:

public void CreateEvent(Event @event)
{
    //How to add event? (so the database will update the user that created the
    //event and also will update the UsersEvents table.
}

I have tried to add the event first, but then had a problem to get the user. Can someone help me and even without a code, just to help me understand how should I do this. Should I add the event and then the user? or should I add the event and the user to the UsersEvents? Thanks in advance :)

Upvotes: 0

Views: 44

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109347

In a pure many to many association (where the junction table is not visible in the class model) you have to add items to the collection of the owner. In your case this would be:

var evnt = new Event { ... };
var user = db.Users.Include(u => u.Events).Single(u => u.UserId == id);
user.Events.Add(evnt);
db.SaveChanges();

The Include is there to make sure that user.Events is loaded before you add an item to it. If it isn't loaded the change tracker won't notice the change and nothing is saved.

But I think I understand your problem. You've implemented a repository pattern, so you feel forced to handle each object by its own repository. A User has nothing to do with an EventRepository, right? So remove this repository layer! In most cases it's just a useless layer that only sandbags everything you want to do with data. To get convinced you may want to read Generic Repository With EF 4.1 what is the point.

Upvotes: 1

Related Questions