如何在带有数据注释的EF Core迁移中将外键设置为NOT NULL?

问题描述 投票:3回答:1

我正在使用ASP.NET Core和EF Core,并且具有以下两个父类和子类。每张礼品卡可以进行很多交易:

public class GiftCard
{
    public int Id { get; set; }
    public string BarCode { get; set; }
    public DateTime PurchaseDate { get; set; }
    public string Comments { get; set; }
    public byte[] Timestamp { get; set; }
    public List<Transaction.Transaction> Transactions { get; set; }
}

public class Transaction
{
    public int Id { get; set; }
    public DateTime TransactionDate { get; set; }
    public decimal TransactionAmount { get; set; }
    public TransactionType TransactionType { get; set; }
    public byte[] Timestamp { get; set; }
    public GiftCard.GiftCard GiftCard { get; set; }
}    

根据我所读的内容,这是通过在父级上具有导航属性而在子级中具有引用导航的方法来实现的。当我添加迁移并使用命令行更新数据库时,数据库中的一切似乎正常,除了Transactions表中的GiftCardId外键是可空的。我想确保这不是空值。我是否缺少数据注释属性?

entity-framework-core ef-migrations
1个回答
3
投票

将以下属性放在您的Transaction实体上,应该将其解析。

public int GiftCardId { get; set; }

您的定义发生了什么事,就是创建了阴影属性,并且EF的变更跟踪器正在维护关系。

请参见here


0
投票

您缺少[Required]属性

© www.soinside.com 2019 - 2024. All rights reserved.