I have two classes:
public class DbLibrary
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<DbDepartment> Departments { get; set; } = new List<DbDepartment>();
}
public class DbDepartment
{
public Guid Id { get; set; }
public string Name { get; set; }
}
In this model I need DbDepartment
hasn't the property contained the link to DbLibrary
. But I need the cascade delete on the database side. For this purpose I add the shadow property to DbDepartment
. It is the foreign key. How to relate the primary key DbLibrary
class with the shadow property?
This is my attempt:
protected override void OnModelCreating(ModelBuilder builder)
{
// Create the shadow property
var id = builder.Entity<DbDepartment>().Property<Guid>("LibraryId");
// Create the relationship for cascade delete
builder.Entity<DbLibrary>().HasMany(n => n.Departments)
.WithOne(m => id /* it is wrong */).OnDelete(DeleteBehavior.Cascade);
}
Shadow properties are properties that aren't defined in your . NET entity class but are defined for that entity type in the EF Core model. The value and state of these properties are maintained purely in the Change Tracker.
Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. Eager loading means that the related data is loaded from the database as part of the initial query.
You can access the shadow property via the DbContext. Entry property and set its value via the CurrentValue property: var context = new SampleContext();
You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.
Shadow properties represent a primitive properties (FK in your case) and cannot be used to create navigation property.
In order to configure the relationship end without navigation property, you use the corresponding Has
/ With
parameterless overload. Whether the FK is shadow or regular property doesn't matter. It matters when you configure the associated FK using HasForeignKey
method, which means that for shadow properties you have to use the overload with string
property name rather than lambda expression.
Here is the desired fluent configuration:
builder.Entity<DbLibrary>()
.HasMany(e => e.Departments)
.WithOne()
.HasForeignKey("LibraryId")
.OnDelete(DeleteBehavior.Cascade);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With