如何在C#数据绑定类中添加非数据库映射字段?
解决方案:标记字段不映射到数据库
你遇到的问题是因为Entity Framework(EF)默认会将实体类的所有公共属性映射到数据库表的列,而新增的ActionType字段在数据库表中不存在,所以执行查询时触发SQL异常。以下是几种常用的解决方法:
方法1:使用[NotMapped]特性
直接在ActionType字段上添加[NotMapped]特性,告诉EF忽略这个属性的数据库映射。需要先引用System.ComponentModel.DataAnnotations.Schema命名空间。
示例代码:
using System.ComponentModel.DataAnnotations.Schema; public class Table1 { public int Id { get; set; } public string Name { get; set; } [NotMapped] public int ActionType { get; set; } }
方法2:使用Fluent API配置
如果不想在实体类中添加特性,可以在DbContext的OnModelCreating方法中通过Fluent API配置忽略该字段:
示例代码:
public class YourDbContext : DbContext { public DbSet<Table1> Table1 { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // 忽略ActionType字段的数据库映射 modelBuilder.Entity<Table1>().Ignore(t => t.ActionType); } }
补充说明
Where子句未报错是因为EF在构建查询表达式时只是生成SQL的逻辑,并没有立即执行数据库查询;当你开始迭代结果(foreach)时,EF才会执行SQL语句,此时数据库找不到对应的ActionType列,就抛出了异常。
内容的提问来源于stack exchange,提问作者user22019322
相关产品推荐
相关产品推荐

