如何在Entity Framework Core中命名外键

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

CollectionmodelItemModel之间的一对多关系(过度简化的示例):

[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; }
}

基本上,它与此exampel相对应(尽管是实体框架6)。我已经遇到过一些Fluent API使用的一些stackoverflow线程,但是希望避免使用它们(即,我遇到其他一些问题。)当我迁移域时(与Entity Framework处于一个单独的项目中)以下名称FK_Items_Collections_ItemModelId有点长。

我想念什么吗?

感谢您的见解。

askeric 回答:如何在Entity Framework Core中命名外键

这不是使用注释创建外键的正确方法。您应该创建以下内容:

{{1}}
,

在以下情况下,当键与属性名称+ ID匹配时,您不需要任何属性

@

上面代码的迁移会生成

user@&#65279;example.com

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

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);
    });
本文链接:https://www.f2er.com/1357464.html

大家都在问