Two different objects with same key for entity framework does not work

前端 未结 2 2131
余生分开走
余生分开走 2021-02-19 20:11

I am trying to insert object reference in my main object but EntityFramework will complain if I don\'t use its previously managed object. I simply want to avoid having a depende

相关标签:
2条回答
  • 2021-02-19 20:56

    if the same ApplicationUser has been previously loaded by the context, I get this error

    So first check if the ApplicationUser is loaded.

    var newId = 2;
    var newApplicationUser = db.ApplicationUsers.Local.FirstOrdefault(u => u.Id == newId)
                                 ?? new ApplicationUser { Id = newId };
    myMovie.Owner = newApplicationUser;
    
    0 讨论(0)
  • 2021-02-19 21:07

    If you have an instance where you are only reading data and not modifying it you can use AsNoTracking() this will prevent having an attached instance of the model that your context knows about (it is essentially read only).

    The following code should work even though it has retreived the same object twice.

    var myMovieReadOnly = db.Movies.AsNoTracking().FirstOrDefault(m, m => m.Id = 1);
    
    var myMovie = db.Movies.FirstOrDefault(m, m => m.Id = 1);
    myMovie.Owner = new ApplicationUser { Id = 2 };
    
    db.SaveChanges();
    

    Another note is that AsNoTraking() can also save on performance in scenarios where you are only reading data.


    Edit: Just reread and realized it is the ApplicationUser model and not the movie, but the same concept should apply with retreival of the first instance.


    Edit2:

    From our comments you could also do the following the prevent needing to do the lookup at all if you already know the ID:

    class Movie {
        public int OwnerId { get;set; }
        public ApplicationUser Owner { get;set; }
    }
    
    var myMovie = db.Movies.FirstOrDefault(m, m => m.Id = 1);
    myMovie.OwnerId = 2;
    db.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题