Configuring your models with Entity Framework

One of the tricks I’ve used for a while when setting EF up in a project, is to use inheritance in order to share code, but not objects, across the business and data layers of the application.

Let’s take the following example, as shown above:

namespace MyProject.Models
{
    public class ResourceModel
    {

And now the data layer:

namespace MyProject.Data.Resources
{
    public class ResourceEntity : ResourceModel

This gives us a number of advantages: the code is shared between the objects, but the two objects are not the same. However, until recently, this presented an issue. Imagine that we had a property in the model that looked like this:

public TagModel[] Tags { get; } 

TagModel itself might have a similar inheritance structure; however, how would you return that from the data layer – since the inheritance would force it to return the same type.

Covariance return type

Fortunately, since C# 9 you can return covariants (Covariance is basically the idea that you can substitute a sub-type for a class).

What this means is that you can override the relevant property in the sub class (the data layer). First, you’ll need to make the property virtual:

    public class ResourceModel
    {
        public virtual TagModel[] Tags { get; } 
    }

And then just override it:

    public class ResourceEntity : ResourceModel
    {
        public int Id { get; set; }

        public override TagEntity[] Tags { get; }
    }

You can’t use anything like a List here, because (for example) a List of TagEntity has no relationship to a List of TagModel.

Hope this helps.

References

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/covariant-returns?WT.mc_id=DT-MVP-5004601

https://github.com/dotnet/csharplang/issues/49

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override?WT.mc_id=DT-MVP-5004601

1 thought on “Configuring your models with Entity Framework

  1. Pingback: Dew Drop – June 27, 2022 (#3710) – Morning Dew by Alvin Ashcraft

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.