MySql中的多对多关系问题

时间:2016-10-27 21:47:38

标签: mysql asp.net-core entity-framework-core .net-core

我正在使用带有SapientGuardian's EFCore library的MySQL的EF Core,我正在尝试使用以下代码创建一个具有多对多关系的表;

        public class Personnel
        {
            public int Id { get; set; }

            [MaxLength(100)]
            public string Name { get; set; }

            public virtual ICollection<PersonnelDegree> PersonnelDegrees { get; set; }
        }

        public class Degree
        {
            public int Id { get; set; }

            [MaxLength(100)]
            public string Name { get; set; }

            public virtual ICollection<PersonnelDegree> PersonnelDegrees { get; set; }
        }

        public class PersonnelDegree
        {
            public int PersonnelId { get; set; }

            public int DegreeId { get; set; }

            public virtual Personnel Personnel { get; set; }

            public virtual Degree Degree { get; set; }
        }

        // Inside the OnModelCreating override
        builder.Entity<Degree>().HasMany(x => x.Personnel);
        builder.Entity<Personnel>().HasMany(x => x.Degrees);

        builder.Entity<PersonnelDegree>()
            .HasKey(x => new { x.DegreeId, x.PersonnelId });

        builder.Entity<PersonnelDegree>()
            .HasOne(x => x.Degree)
            .WithMany(x => x.PersonnelDegrees)
            .HasForeignKey(x => x.DegreeId);

        builder.Entity<PersonnelDegree>()
            .HasOne(x => x.Personnel)
            .WithMany(x => x.PersonnelDegrees)
            .HasForeignKey(x => x.PersonnelId);

现在,当我运行dotnet ef migration添加人员时;我明白了......

        migrationBuilder.CreateTable(
            name: "Role",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("MySQL:AutoIncrement", true),
                ApplicationId = table.Column<int>(nullable: true),
                Name = table.Column<string>(maxLength: 100, nullable: true),
                PersonnelId = table.Column<int>(nullable: true) // Where is this coming from?
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Role", x => x.Id);
                table.ForeignKey(
                    name: "FK_Role_Application_ApplicationId",
                    column: x => x.ApplicationId,
                    principalTable: "Application",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

请注意,表定义中的Role具有PersonnelId列。 Personnel表有RoleId吗?谁能告诉我这里发生了什么?

1 个答案:

答案 0 :(得分:0)

我有相同的模型,但有不同的OnModelCreating方法。

所以我假设您配置错误。对于你的情况应该是这样的:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<PersonnelDegree>()
            .HasKey(t => new { t.PersonnelId , t.DegreeId });
    }

这就是你在OnModelCreating方法中应该拥有的一切。