实体框架核心2拥有的实体类型-更改表列的名称

时间:2019-11-19 15:51:05

标签: c# asp.net-core ef-core-2.1

我有实体类,像这样:

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

    public int ModelId { get; set; }

    public Model Model { get; set; }

    public Contact Contact { get; set; }
}

[Owned]
public class Contact
{
    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    [StringLength(255)]
    public string Email { get; set; }

    [Required]
    [StringLength(255)]
    public string Phone { get; set; }
}

它将默认生成表格:

 migrationBuilder.CreateTable(
            name: "Bike",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                ModelId = table.Column<int>(nullable: false),
                Contact_Name = table.Column<string>(maxLength: 255, nullable: false),
                Contact_Email = table.Column<string>(maxLength: 255, nullable: true),
                Contact_Phone = table.Column<string>(maxLength: 255, nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Bike", x => x.Id);
                table.ForeignKey(
                    name: "FK_Bike_Models_ModelId",
                    column: x => x.ModelId,
                    principalTable: "Models",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            });

您会看到列名称为:Contact_Name, Contact_Email, Contact_Phone
如何摆脱"_"以获得ContactName ...?

3 个答案:

答案 0 :(得分:2)

明确命名列:

modelBuilder.Entity<Order>().OwnsOne(
    o => o.ShippingAddress,
    sa =>
    {
        sa.Property(p => p.Street).HasColumnName("ShipsToStreet");
        sa.Property(p => p.City).HasColumnName("ShipsToCity");
    });

https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities

答案 1 :(得分:1)

另一个更复杂的示例(嵌套的实体)看起来

let window = app.android.startActivity.getWindow();
window.setStatusBarColor(new Color("black").android);

答案 2 :(得分:0)

您可以覆盖OnModelCreating的{​​{1}}方法,以避免显式命名每个列名。

以下示例将从列名称中删除下划线:

DbContext