实体框架6添加了新的多对多关系

时间:2014-07-20 12:30:49

标签: entity-framework many-to-many entity-framework-6

我首先在MVC 5中使用EF6代码。我有两个对象MovieUser,每个对象都有另一个对象(多对多)。使用现有的User,我正在尝试将UserMovie关联,但不会将任何行插入数据库。 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模型 - 意味着MovieUser : 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"));
    }
}

我发现此exampleuser.Movies没有附加方法,因为它只是ICollection

在EF6中以多对多关系将两个对象相互关联的正确方法是什么?

0 个答案:

没有答案