.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
相关产品推荐
相关产品推荐

