How do you make foreign key as NOT NULL in EF Core migrations with Data Annotations?

ef-migrations entity-framework-core

Question

I'm using ASP.NET Core and EF Core and I have the two following parent and child classes. Each gift card can have many transactions:

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

Based on what I read, this is the way to do it, by having navigation property on the parent and reference navigation in child. When I add my migrations and update the database using the command line, everything seemed ok in the database except that the GiftCardId foreign key in the Transactions table is nullable. I want to make sure this is NOT NULL. Am I missing a Data Annotation attribute?

1
3
9/19/2016 8:14:35 PM

Accepted Answer

Put the following property on your Transaction entity, and it should be resolved.

public int GiftCardId { get; set; }

What is happening with your definition is that a shadow property is being created and EF's Change Tracker is maintaining the relationships.

See here.

4
9/19/2016 8:44:31 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow