我有以下数据模型:
public class Foo
{
public Foo(int barId)
{
BarId = barId;
}
private int BarId;
public Bar Bar { get; private set; }
}
public class FooTypeConfig : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.HasOne(x => x.Bar)
.WithMany()
.HasForeignKey("BarId");
}
}
public class Bar
{
public int Id { get; private set; }
}
这很好用,根据我的期望,我有一个Foo
表包含Id
and BarId
。我的私人领域BarId
and my Bar
阅读时属性也能正确实现Foo
从数据库中。
问题是我想找到一种方法来命名我的私有字段,并为我的数据库列选择不同的名称。我想为我的财产命名_barId
并仍然选择BarId
作为我数据库中的列名。
这可能吗?
我尝试过重命名我的字段Foo
类并指定我的(现在非常规命名的)外键_barId
in my EntityTypeConfiguration
builder.HasOne(x => x.Bar).WithMany().HasForeignKey("_barId");
但这导致 EF 仍然生成BarId
列,而不将其用作外键Bar
桌子...
migrationBuilder.CreateTable(
name: "Foos",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BarId = table.Column<int>(nullable: true),
_barId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Foos", x => x.Id);
table.ForeignKey(
name: "FK_Foos_Bars__barId",
column: x => x._barId,
principalTable: "Bars",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});