在我的模型中,我与同一张桌子有2对多的关系。像这样:
public class BpsModel {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Person> Reviewers { get; set; }
public List<Person> Modelers { get; set; }
}
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
当我运行迁移时,这是数据库Person表的结构:
migrationBuilder.CreateTable(
name: "Persons",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
BpsModelId = table.Column<int>(nullable: true),
BpsModelId1 = table.Column<int>(nullable: true),
Email = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.Id);
table.ForeignKey(
name: "FK_Persons_BpsRecords_BpsModelId",
column: x => x.BpsModelId,
principalTable: "BpsRecords",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Persons_BpsRecords_BpsModelId1",
column: x => x.BpsModelId1,
principalTable: "BpsRecords",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
如您所见,Person表有两列名称非常相似的列:BpsModelId
和BpsModelId1
。这没有用,因为我现在必须去挖掘哪一个是Modeler,哪一个是Reviewer。有没有办法将列名更改为ReviewerBpsModelId
和ModelerBpsModelId
?
由于
答案 0 :(得分:2)
在OnModelCreating
方法中,您应该使用如下所示的流畅配置进行设置:
modelBuilder.Entity<BpsModel>()
.HasMany(p => p.Reviewers)
.WithOne()
.HasForeignKey("BpsModelReviewerId"); // <- You customize the foreign key name for Reviewers association
modelBuilder.Entity<BpsModel>()
.HasMany(p => p.Modelers)
.WithOne()
.HasForeignKey("BpsModelModelerId"); // <- You customize the foreign key name for Modelers association
答案 1 :(得分:0)
如果希望[KEY]在数据库中具有某个名称,则可以在模型类中使用DataAnnotations来配置SQL Server列名。这称为Column Mapping
所以你可以这样做:
public class BpsModel {
[Key]
[Column("my_custom_column_name")]
public int Id { get; set; }
public string Name { get; set; }
public List<Person> Reviewers { get; set; }
public List<Person> Modelers { get; set; }
}
答案 2 :(得分:0)
这是因为您需要两个Int字段,一个用于存储Modeler代码,另一个用于Reviewer,问题是这两个键由同一个表引用。所以要解决问题。
Reviewer的外键
[ForeignKey("ReviewerId")]
public int ReviewerId { get; set; }
public Person Reviewers { get; set; }
Modeler的外键
[ForeignKey("ModelerId")]
public int ModelerId { get; set; }
public Person Modelers { get; set; }
你的课程看起来像这样
public class BpsModel {
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("ReviewerId")]
public int ReviewerId { get; set; }
public Person Reviewers { get; set; }
[ForeignKey("ModelerId")]
public int ModelerId { get; set; }
public Person Modelers { get; set; }
}
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public ICollection<BpsModel> BpsModel{ get; set; }
}
添加使用:
using System.ComponentModel.DataAnnotations.Schema;
运行添加迁移,它在我的项目中工作!