I'm using EF6 code first with MVC 5. I have two objects, Movie
and User
, with each object having a collection of the other (many-to-many). Using an existing User
, I'm trying to associate that User
to a Movie
but no rows are being inserted into the database. The Movie
could be existing or new, but either way the association is not being created.
Movie
is just a simple POCO
User
inherits from IdentityUser
public class User : IdentityUser {
public virtual ICollection<Movie> Movies { get; set; }
public User() {
Movies = new Collection<Movie>();
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) {
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
My Controller Action:
public async Task<HttpResponseMessage> Post(Movie rawMovie) {
try {
var movie = _store.Movies.Get(m => m.Id == rawMovie.Id).FirstOrDefault();
if (movie == null) {
movie = rawMovie;
_store.Movies.Insert(movie);
movie.Cast.Where(n => _store.Cast.Get(e => e.Id == n.Id).Select(e => e.Id).Contains(n.Id))
.ToList()
.ForEach(c => _store.Context.Entry(c).State = EntityState.Unchanged);
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if(user == null) return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid User");
user.Movies.Add(movie);
return Request.CreateResponse(_store.SaveChanges());
} catch (Exception e) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
I use the new IdentityDbContext as my single context, so it's used for both authentication and my POCO models - meaning that both Movie
and User : IdentityUser
share the same the context.
public class ApplicationContext : IdentityDbContext<User> {
public DbSet<Movie> Movies { get; set; }
public DbSet<Character> Cast { get; set; }
public ApplicationContext()
: base("MoovyConnection", throwIfV1Schema: false) { }
public static ApplicationContext Create() {
return new ApplicationContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Movie>().HasMany(m => m.Cast).WithMany(c => c.Movies)
.Map(t => t.MapLeftKey("Movid_Id").MapRightKey("Character_Id").ToTable("MovieCharacters"));
}
}
I've found this example but user.Movies
does not have an attach method as it is only an ICollection
.
What is the proper way to associate two objects to each other in a many-to-many relationship in EF6?