簡體   English   中英

Entity Framework Core 2 擁有的實體類型 - 更改表列的名稱

[英]Entity Framework Core 2 Owned Entity Types - Change Names of Table Columns

我有實體類,如下所示:

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 ...?

明確命名列:

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

另一個更復雜的例子(嵌套擁有的實體)看這個

            empleador.OwnsOne(
            property => property.RepresentanteLegal,
            configuration =>
            {
                configuration.Property(repLegal => repLegal.Nombre).HasColumnName("Nombre").HasMaxLength(500);
                configuration.OwnsOne(
                    property => property.Rut,
                    rutConfiguracion =>
                    {
                        rutConfiguracion.Property(rut => rut.DigitoVerificador).HasColumnName("RepLegalRutDv");
                        rutConfiguracion.Property(rut => rut.Numero).HasColumnName("RepLegalRutNumero");
                    });
            });

您可以覆蓋DbContextOnModelCreating方法,以避免顯式命名每個列名。

以下示例將刪除列名中的下划線:

public class MyDbContext : DbContext
{    
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        foreach(var entity in builder.Model.GetEntityTypes())
        {           
            foreach(var property in entity.GetProperties())
            {
                property.Relational().ColumnName = property.Relational().ColumnName.Replace("_", String.Empty);
            }
        }
    }
}

spidyx 答案在擁有類型的情況下不起作用,因為它們的定義位於導航中。

但是無論如何,在已經在模型構建器中設置了 OwnsOne 之后,我試圖找到一種更“反思方式”的方法,這里有一個片段:

private void SetupNamesConvention(ModelBuilder modelBuilder)
{   
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var navigation in entityType.GetNavigations().Where(x => x.ClrType == typeof(YOUR_OWNS_ONE_PROPERTY)))
        {
            foreach (var fkProperty in navigation.ForeignKey.DeclaringEntityType.GetProperties())
            {
                // your code to set naming conventions
                ...
                fkProperty.Relational().ColumnName;
                ...
            }
        }
    }
}

如果通過以下方式進行操作可能會很有用:

.OwnsOne(e => e.Address, cb => { cb.Property(e => e.Postcode).HasColumnName("Postcode"); });

不是最佳的,就像您有一些自定義邏輯可以遍歷每個屬性並設置命名約定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM