3

I have designed my models so that it should not be created with a null parameter. For example, if I want to enforce that every Post should have a corresponding Blog, then my models will look like:

public class Post
{
    private Post() { }
    public Post(Blog blog)
    {
        Blog = blog ?? throw new ArgumentNullException(nameof(blog));
    }
    public int PostId { get; private set; }
    public Blog Blog { get; private set; }
}
public class Blog
{
    public int BlogId { get; private set; }
}

This way, it will throw an Exception if blog is null.

But I use EF Core and it fails this test.

public class Tests
{
    [Fact]
    public void Test()
    {
        using (var ctx = new Context())
        {
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
            ctx.Add(new Post(new Blog()));
            ctx.SaveChanges();
        }
        using (var ctx = new Context())
        {
            var post = ctx.Post.First();
            Assert.NotNull(post.Blog); //fail
        }
    }
}
public class Context : DbContext
{
    public DbSet<Post> Post { get; set; }
    public DbSet<Blog> Blog { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>(b => b.HasOne(p => p.Blog));
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlite("datasource=db.sqlite");
}

I know that it's because EF Core calls the private constructor without parameters and that I need to load (i.e. Eager, Explicit, or Lazy) the Post.Blog navigational property.

But what I want to know is if my approach on the design of my EF models are incorrect since EF Core defeats the purpose of constructor with null checking?

EDIT: With C#8's nullable reference types, EF Core may head into the direction where it can set navigational properties using a constructor. See EF Core issue: Support C# nullable references

4
  • Can you explain why it would defeat the purpose? Are you looking for Blog to be absolutely always loaded? That doesn't make a lot of sense to me Jun 28, 2018 at 23:00
  • My thinking is that if Post cannot be constructed with a null Blog, then all my Post instances will never have null Blog. Jun 28, 2018 at 23:19
  • Your constructor makes every post have one blog. If this is saved correctly into the database, then obviously every post you will retrieve from there will have a blog. If you want to make sure, you can always make the navigation property required. Enforcing eager loading to guarantee data integrity is not a good idea, since this is the job of the DBS. Also, EF only calls the constructor to materialize the results (convert the rows of the result set into objects), where it obviously couldn't provide some additional parameter. Jun 29, 2018 at 4:06
  • 1
    You could map your database objects onto a POCO and have that enforce any rules you desire. That way you can explicitly throw errors in POCO mapping that explains what went wrong when people use your objects. Otherwise devs have to research what's giving them vague EF errors instead of realizing that it's a business rule a certain entity must be materialized in the result set.
    – Wurd
    Jun 29, 2018 at 9:52

1 Answer 1

2

TL;DR

You can explicitly define the foreign key in your object model that the database model uses to represent the Post/Blog relationship.

public class Post
{
    private Post() { }
    public Post(Blog blog)
    {
        Blog = blog ?? throw new ArgumentNullException(nameof(blog));
    }
    public int PostId { get; private set; }
    public int BlogId {get; private set; } # Foreign Key Property
    public Blog Blog { get; private set; }
}
public class Blog
{
    public int BlogId { get; private set; }
}

Then you can rewrite your test to check this foreign key for null values.

public class Tests
{
    [Fact]
    public void Test()
    {
        using (var ctx = new Context())
        {
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
            ctx.Add(new Post(new Blog()));
            ctx.SaveChanges();
        }
        using (var ctx = new Context())
        {
            var post = ctx.Post.First();
            Assert.NotEqual(0, post.BlogId); //passes
        }
    }
}
public class Context : DbContext
{
    public DbSet<Post> Post { get; set; }
    public DbSet<Blog> Blog { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>(b => b.HasOne(p => p.Blog));
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlite("datasource=db.sqlite");
}

An alternative to this is to tell your entity model to include the navigation property when you select the post.

public class Tests
{
    [Fact]
    public void Test()
    {
        using (var ctx = new Context())
        {
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
            ctx.Add(new Post(new Blog()));
            ctx.SaveChanges();
        }
        using (var ctx = new Context())
        {
            var post = ctx.Post.Include(p=>p.Blog).First();
            Assert.NotNull(post.Blog); //passes
        }
    }
}
public class Context : DbContext
{
    public DbSet<Post> Post { get; set; }
    public DbSet<Blog> Blog { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>(b => b.HasOne(p => p.Blog));
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlite("datasource=db.sqlite");
}



Detailed Explanation

Your approach is correct if your design warrants it. What is incorrect is your understanding of the separation of responsibilities. We have multiple areas of concern in play:

  1. Object Model & Invariants
  2. Entity Model & Object Relation mapping
  3. Database Model, Constraints, & Referential Integrity

EF Core is responsible for #2. EF Core needs to know the structure of both your object model and database model to successfully map between the two. You can specify Database Constraints in the Object Model or the Entity Model, to help you catch violations of those constraints before making a trip to the database, but they aren't required.

Let's look at two scenarios.

Scenario 1

We want to insert new records into our table, using your apps code to help the user craft the record before committing it to the database. We start in area of concern #1, your object model.

Depending on how you modeled your objects, you might want certain invariants enforced. In your example you have the rule that every Post object belongs to a Blog object. The fact that every Post record in the table has an associated Blog record, is purely a side effect of this invariant.

Scenario #2

You want to select a record from your table, using your apps code to represent that in memory so you can display it to the user. We start in area of concern #3, your database model.

Your database enforces referential integrity with foreign keys, i.e. BlogId. In EF Core you don't need to define this foreign key on your Post object. EF Core will create a shadow property for you base on your Post's navigation property Blog. A shadow property is simply one that exists in the database model but not your object model.

When asking the database model for it's records, it requires you to be very specific about which relations to include. It will not default to joining all foreign keys to their respective tables, you need to do this explicitly. Your entity model doesn't do this automatically for you either. You need to call .Include in your select statement to fill the navigation properties of your object model.

As far as the database model and your entity model are concerned, the referential integrity exists, and is mapped properly to your object model. The result, your object model's invariant is not enforced, because you started with the database model's representation of the data and worked your way back to your object model's representation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.