是否可以通过用于转换值的属性的 setter 来设置属性?

时间:2021-02-12 23:29:38

标签: c# asp.net-core

我们将 EFCore 与 Azure SQL 数据库一起使用。其中一列 Yodels 是一个 tinyint,它只能映射到 C# 中的一个字节,但我们希望将它与需要 bool 的 Web 表单上的复选框一起使用。为了显示它,我们通过附加属性 YodelsBool 访问它,该属性将它转换为 bool。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte Yodels { get; set; }

    public bool YodelsBool
    {
        get {
            return Yodels > 0;
        }
    }
}

表单上的复选框:<input asp-for="Person.YodelsBool" class="form-control" type="checkbox" value="Person.YodelsBool" />

我们还希望能够通过此 YodelsBool 属性设置值。那可能吗?当我们添加一个 setter 时,它会失败 Invalid column name 'YodelsBool',因为它正在尝试为该特定属性更新数据库。

我们尝试了一个二传手:

    public bool YodelsBool
    {
        get {
            return Yodels > 0;
        }
        set {
                Yodels = Covert.ToByte(value);
        }
    }

我们如何在不更改数据库的情况下完成这项工作?我们正在使用 tinyint,以防将来某个时候我们想扩展到 true/false 之外。

1 个答案:

答案 0 :(得分:3)

[NotMapped] 添加到属性:

[NotMapped]
public bool YodelsBool
{
    get {
        return Yodels > 0;
    }
    set {
            Yodels = Covert.ToByte(value);
    }
}