EF Core: How to add the relationship to shadow property?

c# entity-framework entity-framework-core

Question

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);
}
1
4
12/5/2017 7:45:05 AM

Accepted Answer

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);
8
12/5/2017 9:47:40 AM


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