0

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 :)

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
  • Adding new data depends on your model (context). If you have only two entities User and Event you have to create User than create Event and add Event to User collection than save context. If you have three entities. You have to add new one for each of that and save context. In last variant UserEvents has to have navigation props with foreing keys. That is way it would be enought – Vladimir Shmidt Feb 04 '14 at 21:07

1 Answers1

1

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.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291