Join Richard Goforth for an in-depth discussion in this video Using Shadow Properties, part of Accessing Existing Databases with Entity Framework Core.
- View Offline
- [Teacher] Earlier, we added fields to the model that were not on the database. Now we're going to go the other direction and have database fields not on our model. These fields are called Shadow Properties. Shadow Properties are another way that we can separate our code from the gritty details of the database. A simpler model reduces the mental lode when developing against it, and can reduce bugs and errors in the resulting code. If a field with a similar name shouldn't be used in the application, removing it from the model is an easy way to prevent it's use.
Shadow Properties are created by convention when in a model, a relationship exists but the foreign key property doesn't. If we look at our order model, we can see we have a relationship to customer and to sales person. We also have customer ID and sales person ID. These are the foreign keys for that relationship. Having these foreign keys in the model can be particularly useful, and when we scaffold the database, they will always be created. If we add a new relationship or a new table and don't add the foreign key to the model, a Shadow Property would be created automatically.
In general, I try to avoid this and always add a foreign key for each relationship. Using a foreign key in the model can prevent an extra trip to the database when updating an item. If customer ID is not here, and I want to add a customer to the order, I have to assign the whole customer object rather than just the ID. The second use case for Shadow Properties is to hide fields that we don't want to see in our model. For an example of this, let's go back to the sales person model.
This application isn't going to use any of the address fields for a sales person. So we're going to remove them from the model. Now that we've removed them from the model, we'll define them as Shadow Properties in our context. Shadow Properties cannot be defined with data annotations because there's no properties in the model to attach the annotations to. We'll scroll down now to the sales person model definition. We can see where our missing fields are causing errors. To change these to Shadow Properties, we need to provide the type since the type is no longer provided in the model.
We'll use strings to define the name of the field rather than using the properties themselves. Now only your framework knows about these properties, and we've hid them from the models. We can use Shadow Properties to reduce complexity in the model, and make legacy databases easier to code against.
- Setting up your project
- Connecting to a legacy database
- Scaffolding an initial model and context
- Improving the model
- Updating properties and indexes
- Adding concurrency tokens and timestamps
- Creating complex relationships
- Working with non-Microsoft databases such as SQLite and PostgreSQL