Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core default values for missing columns

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.

like image 437
Willie Avatar asked Oct 28 '25 06:10

Willie


1 Answers

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.

like image 156
Ian Kirkpatrick Avatar answered Oct 29 '25 21:10

Ian Kirkpatrick