How to check the shadow properties of an entity in EF Core?
Shadow properties are not defined in an entity class but they are configured for an entity in the entity data model.
Consider the following two entities.
public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public DateTime? DateOfBirth { get; set; } public decimal Height { get; set; } public float Weight { get; set; } public Grade Grade { get; set; } } public class Grade { public int GradeId { get; set; } public string GradeName { get; set; } public string Section { get; set; } }
In the above example, Student and Grade have a one-to-many relationship. However, a foreign key property for Grade in the Student is not defined. So, by default, EF Core will create a showdown property GradeId for the Student entity.
You can now get all the shadow properties of an entity using property.Metadata.IsShadowProperty, as shown below.
using (var context = new SchoolContext()) { var std = new Student(){StudentName = "Bill" }; var properties = context.Entry<Student>(std).Properties; foreach (var property in properties) { if (property.Metadata.IsShadowProperty) { Console.WriteLine(property.Metadata.Name); } } }
You can also use ChangeTracker if you want to get shadow properties of added or modified entities, as shown below.
using (var context = new SchoolContext()) { var properties = context.ChangeTracker.Entries<Student>().FirstOrDefault().Properties; foreach (var property in properties) { if (property.Metadata.IsShadowProperty) { Console.WriteLine(property.Metadata.Name); } } }
Visit Shadow Property in EF Core for more details.