简体   繁体   English

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

[英]C# - Adding data to objects with a Many-to-Many relationship

I'm creating a webapp where you can see which Teacher has which skills. 我正在创建一个Webapp,您可以在其中查看哪个老师具有哪些技能。 For this I'm working with a code first migration (entitity framework) which is working great so far. 为此,我正在使用代码优先迁移(实体框架),该方法到目前为止效果很好。

Here's how my model is looking 这是我的模特的样子

[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);
    }
}

and this is the migration that has been generated (so you can have a feel for how the DB looks) 这就是已经生成的迁移 (因此您可以了解数据库的外观)

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);
}

I also generated the controllers for both Teachers and Sills, so I can add, edit and delete teachers and skill with ease. 我还为“教师”和“基石”生成了控制器,因此我可以轻松地添加,编辑和删除教师和技能。

My question is , how can I give a teacher a certain skill? 我的问题是 ,我该如何给老师一些技能? Can I also generate a controller for this or do I need to create this myself? 我是否可以为此生成控制器,还是需要自己创建一个控制器? And if so, is there any optimal way I can do this? 如果是这样,我有什么最佳方法可以做到这一点吗?

Looking forward to any help! 期待任何帮助!

Assuming that you have this Seed data 假设您有此种子数据

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();
}

To add a skill for a teacher you must load the teacher from database, then you check if the Skills property is null, if it is create a new list of skill, then find the skill from database that you want to give and use the method add, see code below. 要为老师添加技能,您必须从数据库中加载老师,然后检查Skills属性是否为null,是否正在创建新技能列表,然后从数据库中找到要提供的技能并使用该方法添加,请参见下面的代码。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM