EntityFrameworks inserts already inserted related item

Viewed 61

Im trying to create a user, then connect that user to an model called Event.

var user = new ApplicationUser { name = "test", email = "test@test.com" };
var userResult = UserManager.Create(user, "password");
if (userResult.Succeeded)
{
     SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: true);
     @event.CreatedBy = user;
     @event.CreatedById = new Guid(user.Id);
     db.Events.Add(@event);
     db.SaveChanges();
}

But db.SaveChanges() throws an validation error on the ApplicationUser model: user with the email already exists: test@test.com (even though it didnt exists before this request)

So it would seem as EF is trying to reinserted the already inserted user.

The Event model have these setters/getters

public virtual ApplicationUser CreatedBy { get; set; }
public virtual Guid CreatedById { get; set; }

And it works great if i would get the current singned in user instead of signing up a new one.

I have tried only to set @event.CreatedById and skip @event.CreatedBy, but then EF doesnt save the reference to the database.

1 Answers
Related