I have an application with Entity Framework Core with different entities in my context, but there are two of them that require a one-to-zero-or-one relation. My way of doing that and ensuring validation was to do something like the following:
public class PurchasedPackage
{
public int Id { get; set; }
...
[ForeignKey(nameof(PurchasedPackageModifier))]
public int? PurchasedPackageModifierId { get; set; }
public virtual PurchasedPackageModifier PurchasedPackageModifier { get; set; }
}
And
public class PurchasedPackageModifier
{
public int Id { get; set; }
...
[Required]
[ForeignKey(nameof(PurchasedPackage))]
public int PurchasedPackageId { get; set; }
public virtual PurchasedPackage PurchasedPackage { get; set; }
...
}
Where PurchasedPackage
is required and PurchasedPackageModifier
is optional. By specifying ForeignKey
attribute on both sides I'm trying to ensure data integrity across saves to both tables so nobody creates a PurchasedPackage
with a non-existent PurchasedPackageModifier
and vice versa.
While this works as required I'm getting warnings in my logs stating the following:
'PurchasedPackage.PurchasedPackageModifier' and 'PurchasedPackageModifier.PurchasedPackage' were separated into two relationships as ForeignKeyAttribute was specified on properties 'PurchasedPackageModifierId' and 'PurchasedPackageId' on both sides.
And
'PurchasedPackageModifier.PurchasedPackage' and 'PurchasedPackage.PurchasedPackageModifier' were separated into two relationships as ForeignKeyAttribute was specified on properties 'PurchasedPackageId' and 'PurchasedPackageModifierId' on both sides.
My question is: am I doing this right and should I ignore these warnings in this particular case or there is a better way of achieving same validation/integrity behavior?
This issue about warnings is closed in April 2018. I did try your two classes now with mysql(pomelo lib) and indeed I get one FK. So if this is acceptable to you you can ignore the warnings (to quote one of the devs from that github link)
If you really want the "one-to-zero-or-one relation", then the following approach is how I'd do it:
PurchasedPackage
has no FK to PurchasedPackageModifier
, by this I mean remove both int? PurchasedPackageModifierId
int? PurchasedPackageModifierId
and the navigation property urchasedPackageModifier PurchasedPackageModifier
- this covers 1-0 part where a record in PurchasedPackage
can exist without corresponding PurchasedPackageModifier
existing PurchasedPackageModifier
has a column PurchasedPackageId
which is FK to PurchasedPackage
and also an unique index - this covers 1-1 part where
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.