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

时间:2016-09-19 20:14:35

标签: entity-framework-core ef-migrations

我使用的是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外键可以为空之外,数据库中的一切似乎都正常。我想确保这不是NULL。我错过了数据注释属性吗?

1 个答案:

答案 0 :(得分:3)

将以下属性放在Transaction实体上,并且应该解析它。

public int GiftCardId { get; set; }

您的定义发生的是正在创建一个shadow属性,而EF的Change Tracker正在维护关系。

请参阅here

相关问题