You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中SQLite实体模型添加非数据库存储字段的方案

解决方案

针对你的需求,在.NET Maui常用的SQLite ORM库中,有直接的注解可以标记不映射到数据库的字段:

1. 若使用 sqlite-net(如sqlite-net-pcl)

直接给字段添加 [Ignore] 特性即可,该特性会让ORM忽略此字段,不将其存储到数据库:

修改后的实体代码:

[Table("CheckListItem")]
public class CheckListItem
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(CheckList))]
    public int checkListID { get; set; }
    public string itemText { get; set; }
    public bool isChecked { get; set; }
    public bool isSkipped { get; set; }
    public int itemOrder { get; set; }

    [ManyToOne]
    public CheckList CheckList { get; set; }

    // 新增的不映射字段
    [Ignore]
    public bool isBeingDragged { get; set; }
    [Ignore]
    public bool isDropped { get; set; }

    public (bool IsValid, string ErrorMessage) Validate()
    {
        if (string.IsNullOrWhiteSpace(itemText))
        {
            return (false, $"{nameof(itemText)} is required.");
        }
        return (true, null);
    }
}

2. 若使用 Entity Framework Core SQLite

则使用 [NotMapped] 特性标记不需要存储到数据库的字段:

修改后的实体代码:

[Table("CheckListItem")]
public class CheckListItem
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    [ForeignKey(typeof(CheckList))]
    public int checkListID { get; set; }
    public string itemText { get; set; }
    public bool isChecked { get; set; }
    public bool isSkipped { get; set; }
    public int itemOrder { get; set; }

    [ManyToOne]
    public CheckList CheckList { get; set; }

    // 新增的不映射字段
    [NotMapped]
    public bool isBeingDragged { get; set; }
    [NotMapped]
    public bool isDropped { get; set; }

    public (bool IsValid, string ErrorMessage) Validate()
    {
        if (string.IsNullOrWhiteSpace(itemText))
        {
            return (false, $"{nameof(itemText)} is required.");
        }
        return (true, null);
    }
}

这两种方式都无需额外转换对象,直接在原实体上添加字段并标记即可满足需求。

内容的提问来源于stack exchange,提问作者Gratzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:42:32