如何使用DbContext在多对多表中添加记录

时间:2015-06-06 10:35:49

标签: c# sql-server database

一开始我在sql server中创建了数据库 接下来我使用了实体数据模型(数据库优先),我得到了下面嵌入的代码。

我的数据库模型:

db model

DbModel.cs

public virtual DbSet < Actor > Actor {get;set;}
public virtual DbSet < Genre > Genre {get;set;}
public virtual DbSet < Movie > Movie {get;set;}

public virtual DbSet < sysdiagrams > sysdiagrams {get;set;}

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    modelBuilder.Entity < Actor > ()
        .HasMany(e = > e.Movie)
        .WithMany(e = > e.Actor)
        .Map(m = > m.ToTable("MovieActors").MapLeftKey("ActorID").MapRightKey("MovieID"));

    modelBuilder.Entity < Genre > ()
        .HasMany(e = > e.Movie)
        .WithMany(e = > e.Genre)
        .Map(m = > m.ToTable("MovieGenres").MapLeftKey("GenreID").MapRightKey("MovieID"));

和actor.cs

[Table("Actor")]
 public partial class Actor {
    public Actor() {
        Movie = new HashSet < Movie > ();
    }

    public int ID {get;set;}

    [Required]
    [StringLength(50)]
    public string FirstName {get;set;}

    [Required]
    [StringLength(50)]
    public string LastName {get;set;}

    public virtual ICollection < Movie > Movie {get;set;}
 }

一切正常但是......

using(var db = new MovieDbModel()) {
    var movie = new Movie() {
        Title = "Test",
        Year = 1990
    };


    db.Actor.Add(new Actor {
        FirstName = "Al", LastName = "Pacino"
    });

    db.Genre.Add(new Genre {
        Name = "Action"
    });

    db.SaveChanges();

}

我不知道如何将actor添加到电影中,因为db.MovieActors不存在 我在代码中出错了?

我想插入MovieActors(MovieID,ActorID)VALUES(1,1)但是怎么样?

1 个答案:

答案 0 :(得分:1)

您应该将电影实体添加到actor.Movie集合中,例如:

    using (var db = new MovieDbModel("Server=localhost;Database=test;Trusted_Connection=True;"))
    {
        var movie = new Movie()
        {
            Title = "Test",
            Year = 1990
        };

        var actor = new Actor
        {
            FirstName = "Al",
            LastName = "Pacino"
        };

        db.Actor.Add(actor);

        actor.Movie.Add(movie);

        db.SaveChanges();

    }