C# - 向具有多对多关系的对象添加数据

时间:2016-01-02 13:18:06

标签: c# asp.net-mvc entity-framework many-to-many

我正在创建一个webapp,您可以在其中查看哪位教师具备哪些技能。为此,我正在使用代码优先迁移(权利框架),到目前为止工作得很好。

以下是我的模型的样子

[System.ComponentModel.DataAnnotations.Schema.Table("Skills")]
public class Skill
{
    [key]
    public int ID { get; set; }
    public string SkillName { get; set; }

    public virtual List<Teacher> Teachers { get; set; }
}

[System.ComponentModel.DataAnnotations.Schema.Table("Teachers")]
public class Teacher
{
    [key]
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Campus { get; set; }

    public virtual List<Skill> Skills { get; set; }
}

public partial class AbilityDbContext : DbContext
{
    public AbilityDbContext() : base("name= DefaultConnection")
    {
        Database.SetInitializer<AbilityDbContext>(null);
    }

    public virtual DbSet<Teacher> Teachers { get; set; }
    public virtual DbSet<Skill> Skills { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Teacher>()
        .HasMany(s => s.Skills)
        .WithMany(c => c.Teachers);
        base.OnModelCreating(modelBuilder);
    }
}

这是已生成的迁移(因此您可以了解数据库的外观)

public override void Up()
{
    CreateTable(
        "dbo.Skills",
        c => new
        {
            ID = c.Int(nullable: false, identity: true),
            SkillName = c.String(),
        })
        .PrimaryKey(t => t.ID);

    CreateTable(
        "dbo.Teachers",
        c => new
        {
            ID = c.Int(nullable: false, identity: true),
            FirstName = c.String(),
            LastName = c.String(),
            Email = c.String(),
            Campus = c.String(),
        })
        .PrimaryKey(t => t.ID);

    CreateTable(
        "dbo.TeacherSkills",
        c => new
        {
            Teacher_ID = c.Int(nullable: false),
            Skill_ID = c.Int(nullable: false),
        })
        .PrimaryKey(t => new { t.Teacher_ID, t.Skill_ID })
        .ForeignKey("dbo.Teachers", t => t.Teacher_ID, cascadeDelete: true)
        .ForeignKey("dbo.Skills", t => t.Skill_ID, cascadeDelete: true)
        .Index(t => t.Teacher_ID)
        .Index(t => t.Skill_ID);
}

我还为教师和窗台生成了控制器,因此我可以轻松添加,编辑和删除教师和技能。

我的问题是,我怎样才能给老师一定的技能?我还可以为此生成控制器,还是需要自己创建?如果是这样,有什么最佳方法可以做到这一点吗?

期待任何帮助!

1 个答案:

答案 0 :(得分:1)

假设您有此种子数据

using (var context = new AbilityDbContext())
{
    if (!context.Skills.Any())
    {
        context.Skills.Add(new Skill { SkillName = "C#" });
        context.Skills.Add(new Skill { SkillName = "Java" });
        context.Skills.Add(new Skill { SkillName = "Html" });
        context.Skills.Add(new Skill { SkillName = "Ruby" });
    }

    if (!context.Teachers.Any())
        context.Teachers.Add(new Teacher
        {
            FirstName = "Alberto",
            LastName = "Monteiro",
            Campus = "PICI",
            Email = "alberto.monteiro@live.com"
        });
    context.SaveChanges();
}

要为教师添加技能,您必须从数据库加载教师,然后检查技能属性是否为空,如果它是创建新的技能列表,则从数据库中找到您要提供的技能,使用方法add,参见下面的代码。

using (var context = new AbilityDbContext())
{
    var teacher = context.Teachers.Find(1);

    teacher.Skills = teacher.Skills ?? new List<Skill>();

    teacher.Skills.Add(context.Skills.Find(1));
    teacher.Skills.Add(context.Skills.Find(2));
    context.SaveChanges();
}