Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 278
Andrey Bushman Avatar asked Dec 05 '17 07:12

Andrey Bushman


People also ask

What is shadow property in EF core?

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.

How do I load related data in EF core?

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.

How do I access shadow property?

You can access the shadow property via the DbContext. Entry property and set its value via the CurrentValue property: var context = new SampleContext();

How will you create relationship between tables in Entity Framework?

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.


1 Answers

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);
like image 81
Ivan Stoev Avatar answered Sep 20 '22 01:09

Ivan Stoev