3

我有一个 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+ 列。

4

2 回答 2

1

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

将 NotMapped 作为属性放在 Additional 字段上:

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 该字段不是数据库中的列。

于 2019-12-06T13:33:15.953 回答
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; }
}

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

于 2019-12-06T13:43:57.647 回答