如何在 Entity Framework Core 中命名外键

问题描述 投票:0回答:2

Entity Framework Core 似乎不尊重我指定为 property 属性的外键的自定义名称。我有点担心,因为我认为它最初有效..

CollectionModel
ItemModel
之间的一对多关系(过于简化的示例):

[Table("Collections")]
public class CollectionModel
{
    [Key]
    public int Id { get; set; }
    
    public string name {get; set; }
    
    public List<ItemModel> Items { get; set; }
}

[Table("Items")]
public class ItemModel
{
    [Key]
    public int Id { get; set; }
    
    [ForeignKey("FK_Item_CollectionId")] // No sure if it actually respects the convention..
    public int CollectionId { get; set; }
}

基本上,它对应于这个示例(尽管是实体框架 6)。我已经遇到过一些 Fluent API 使用的 stackoverflow 线程,但更愿意避免它们(即我遇到了一些其他问题..)当我迁移域(位于与实体框架不同的项目中)时,我得到下面的名字

FK_Items_Collections_ItemModelId
有点太长了。

我错过了什么吗?

感谢您的任何见解。

c# entity-framework-core attributes foreign-keys fluent
2个回答
2
投票

在下面的情况下,当 Key 匹配 Property name + Id 时,您不需要任何属性

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

    public virtual ICollection<Child> Children { get; set; }
}

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

    public int ParentId { get; set; }

    public virtual Parent Parent { get; set; }
}

上面代码的迁移会生成

migrationBuilder.CreateTable(
    name: "Children",
    columns: table => new
    {
        Id = table.Column<int>(nullable: false)
            .Annotation("SqlServer:Identity", "1, 1"),
        ParentId = table.Column<int>(nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Children", x => x.Id);
        table.ForeignKey(
            name: "FK_Children_Parents_ParentId",
            column: x => x.ParentId,
            principalTable: "Parents",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
    });

如果将 Key 属性名称更改为其他名称,EF 将无法解析它的 key,因此您必须通过注释手动指定它。

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

    public virtual ICollection<Child> Children { get; set; }
}

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

    public int MyKey { get; set; }

    [ForeignKey("MyKey")]
    public virtual Parent Parent { get; set; }
}

您可以使用流畅的方法来更改约束名称

modelBuilder.Entity<Child>()
    .HasOne(x => x.Parent)
    .WithMany(x => x.Children)
    .HasForeignKey(x => x.MyKey)
    .HasConstraintName("My_Key_name");

1
投票

这不是使用注释创建外键的正确方法。你应该创建这样的东西:

[Table("Collections")]
public class CollectionModel
{
    [Key]
    public int Id { get; set; }
    
    public string name {get; set; }
    
    [ForeignKey("FK_Item_CollectionId")]
    public List<ItemModel> Items { get; set; }
}

[Table("Items")]
public class ItemModel
{
    [Key]
    public int Id { get; set; }
    
    
    public int FK_Item_CollectionId { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.