EF核心ForeignKey属性未在迁移中创建约束

时间:2020-05-29 18:02:59

标签: .net-core entity-framework-core

我目前正在研究.NET core 3.1.2项目,在那里我有各种具有外键关系的类。该数据库是根据“代码优先”原则设计的。

要定义外键约束,我想使用System.ComponentModel.DataAnnotations.Schema中的ForeignKey属性。

以下是我使用的3个类的示例:

    public class Facility
    {
        public Facility()
        {
            this.Id = Guid.NewGuid();
        }

        public Guid Id { get; set; }
        public string Location { get; set; }
        public FacilityType FacilityType { get; set; }
    }
    public class Product
    {
        public Product()
        {
            this.Id = Guid.NewGuid();
        }

        public Guid Id { get; set; }
        public string ProductDescription { get; set; }
        public double UnitPrice { get; set; }
        public double? UnitWeight { get; set; }
        public char VarianceClass { get; set; }
        public char MarginClass { get; set; }

    }
    public class Sale
    {
        public Sale()
        {
            this.Id = Guid.NewGuid();
        }

        public Guid Id { get; set; }
        public DateTime Date { get; set; }

        [ForeignKey(nameof(Product))]
        public Guid ProductID { get; set; }

        [ForeignKey(nameof(Facility))]
        public int Quantity { get; set; }

    }

如您所见,第三类Sale具有两个ForeignKey约束。 之后,我创建并应用迁移,该迁移可以正常工作:

dotnet ef migrations add InitialCreate
dotnet ef database update

Build started...
Build succeeded.
Done.

但是,在生成的迁移文件中,根本没有创建外键约束。 不知何故,我的ForeignKey属性被忽略了。 原因可能是什么,创建迁移时是否需要在其他地方进行配置以启用外键约束?

1 个答案:

答案 0 :(得分:0)

[ForeignKey(“产品”)] enter code here公共引导ID {get;组; } 公共虚拟产品Product {get;组; }