Greetings weary travelers!
Have you heard about Shadow Properties that are part of the Entity Framework?
What are shadow properties?
Shadow properties are properties that aren’t defined in your .NET entity class but are defined for that entity type in the Entity Framework Core model.
The value and state of these properties are maintained purely in the Change Tracker.
Shadow properties are useful when there’s data in the database that shouldn’t be exposed on the mapped entity types.
Example
One interesting way that Entity Framework uses shadow properties is in a one-to-many relationship.
Let’s take a look at an example. (images shown below)
We have two entity classes, a Student entity and a Course entity.
In our case, one student can attend only one course but a course can have more than one student.
The entity class representation will be shown in the images below.
If we create the migrations, update the database and check the Students table, we can see a column named “CourseId”.
Entity Framework creates that column and uses it as a shadow property. That column isn’t exposed in the Student class.
If we now add students to a course, the CourseId of those students will be updated accordingly.
This way Entity Framework knows which student is part of which course without exposing the CourseId property in the Student class.
Can we add custom shadow properties?
We can do that by using the FluentAPI and overriding the OnModelCreating method like this:
modelBuilder.Entity<Student>().Property<string>(“ShadowProperty”);
We add a new migration, update the database and we can see that a new column, “ShadowProperty” has been added to the Students table but it isn’t present on the Student model.
Can we access the value of the shadow property?
Yes, we can. Shadow property values can be obtained and changed through the ChangeTracker API like this:
Student student = dbContext.Students.First();
dbContext.Entry(student).Property(“ShadowProperty”).CurrentValue = “It’s a shadow property!”;
They can also be referenced in LINQ queries via the EF.Property static method:
ICollection<Student> students = dbContext.Students.Where(student => EF.Property<string>(student, “ShadowProperty”) != null).ToArray();
TLDR; Shadow properties are useful when there’s data in the database that shouldn’t be exposed on the mapped entity types. We can add custom shadow properties by using the FluentAPI and overriding the OnModelCreating method.
The value of the property can be obtained and changed through the ChangeTracker API, and shadow properties can be referenced in LINQ queries via the EF.Property static method.
Was this helpful?
If you still need expert help, leave us a message here and tell us what’s bothering you.