Entity Framework Core default values for missing columns

2k views Asked by At

I have a sqlite database which has some tables and columns like the following:

int Id
text Name
text Comment
...

And my object in my project looks like this:

Public Class Entry {
    public int Id { get; set; }
    public String Name { get; set; }
    public String Comment { get; set; }
    public String Additional { get; set; }
}

This can happen, because my programm need to handle different versions of the database. EF Core now trys to access the Additional field of the database but returns an error that it cannot find the field. (Expected behaviour)

Now my question is, if there is a way to ignore this error and return a default value for the property?

I could bypass the error by making the properties nullable. But i don't want to check each property with .HasValue() before accessing it. Because the real database has 50+ columns in the table.

2

There are 2 answers

4
Andre On

I would advise you to split your domain object from that persisted dto object. That way you can have different dtos with different mappings. Now you can instantiate your domain object with your dto and decide inside your domain object what values are the correct default values.

public class Entry
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }
    public string Additional { get; set; }
}

public class EntryDtoV1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }
}

public class EntryDtoV2
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }
    public string Additional { get; set; }
}

Now you only need to create some kind of factory that creates the correct repository depending on what database version you query.

5
Ian Kirkpatrick On

https://www.entityframeworktutorial.net/code-first/notmapped-dataannotations-attribute-in-code-first.aspx

Put NotMapped as an attribute on the Additional field:

using System.ComponentModel.DataAnnotations.Schema;

Public Class Entry {
    public int Id { get; set; }
    public String Name { get; set; }
    public String Comment { get; set; }

    [NotMapped]
    public String Additional { get; set; }
}

This tells EF that the field is not a column in the database.