我首先在MVC 5中使用EF6代码。我有两个对象Movie
和User
,每个对象都有另一个对象(多对多)。使用现有的User
,我正在尝试将User
与Movie
关联,但不会将任何行插入数据库。 Movie
可以是现有的,也可以是新的,但无论如何都不会创建关联。
Movie
只是一个简单的POCO
User
继承自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;
}
}
我的控制器操作:
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);
}
}
我使用新的IdentityDbContext作为我的单个上下文,因此它用于身份验证和我的POCO模型 - 意味着Movie
和User : IdentityUser
共享相同的上下文。
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"));
}
}
我发现此example但user.Movies
没有附加方法,因为它只是ICollection
。
在EF6中以多对多关系将两个对象相互关联的正确方法是什么?