缺少列的实体框架核心默认值

时间:2018-11-22 14:17:04

标签: c# entity-framework-core ef-core-2.1

我有一个sqlite数据库,其中包含一些表和列,如下所示:

int Id
text Name
text Comment
...

项目中的对象如下:

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

这可能发生,因为我的程序需要处理不同版本的数据库。 EF Core现在尝试访问数据库的Additional字段,但是返回一个错误,它找不到该字段。 (预期的行为)

现在我的问题是,是否可以忽略此错误并返回属性的默认值?

我可以通过使属性可为空来绕过错误。但是我不想在访问它之前用.HasValue()检查每个属性。因为实际的数据库表中有50多个列。

2 个答案:

答案 0 :(得分:2)

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

将NotMapped放置为“其他”字段上的属性:

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; }
}

这告诉EF该字段不是数据库中的列。

答案 1 :(得分:1)

我建议您从持久化的dto对象中拆分域对象。这样,您可以拥有具有不同映射的不同dto。现在,您可以使用dto实例化域对象,并在域对象内确定哪些值是正确的默认值。

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; }
}

现在,您只需要创建某种工厂即可根据查询的数据库版本创建正确的存储库。