'EF Core HasOptional WithOptionalDependent
I have the following tables in my database:
Product ResourceAssociation
------- ------------------
Name /-------> Id
ResourceAssociation_Id ------/ SomeProperty
So Product has a ResourceAssociation_Id, which is a FK to the ResourceAssociation table.
This is a legacy application that had an Entity Framework 6 map that contained this piece of code:
HasOptional(t => t.ResourceAssociation).WithOptionalDependent().WillCascadeOnDelete(true);
I'm looking to port this to EF Core. EF Core doesn't have the HasOptional anymore, it seems. I've tried this:
builder.HasOne(t => t.ResourceAssociation)
.WithOne().HasForeignKey("ResourceAssociation_Id")
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade);
I've also tried replacing the WithOne with WithMany. But it doesn't work.
When I try to create a new Product, without a ResourceAssociation (because it isn't required), EF Core still tells me my ModelState is invalid because the ResourceAssociation is null.
I can't specify the property in WithOne (e.g. WithOne(x => x.Product)) because ResourceAssociation is a table that will also be used for other tables (for example Brand also has a ResourceAssociation_Id column pointing to that table).
Is this kind of setup even possible in EF Core? Or will I have to add the different navigation properties to my ResourceAssociation class (ie Product, Brand,...)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
