解决EF使用context.Database.SqlQuery时NotMapped属性列为空null的问题
来源:互联网 发布:js array removeall 编辑:程序博客网 时间:2024/06/07 06:00
有时候我们要为EF中的Model加一个新属性,这个属性不是数据库中的字段,而是从其它表中关联出来的。EF中要标示一个列不是对应表中字段只需要加上NotMapped特性。要使用NotMapped,保证你的项目引用了System.ComponentModel.DataAnnotations.dll,NotMapped特性在命名空间System.ComponentModel.DataAnnotations.Schema下。比如我们有一个Employee实体:
public class Employee{ public int EmployeeId { get; set; } public string EmployeeName { get; set; } [NotMapped] public string CustomerName { get; set; }}
可能你会想到用context.Database.SqlQuery写一句原生的sql为CustomerName赋值,就像下面的代码:
public List<Employee> GetEmployees(){ using (MyContext context = new MyContext()) { return context.Database.SqlQuery<Employee>("select E.EmployeeId, E.EmployeeName, C.CustomerName from Employee E left join Customer C on E.CustomerId = C.CustomerId").ToList(); }}
但是遗憾是上面代码字段CustomerName始终都为空。因为使用context.Database.SqlQuery虽然是传的sql语句,但是它和原生的ADO.NET还是不一样,它还是会走一下EF框架,用NotMapped标示的字段,EF会忽略掉这个字段,当生成sql语句也不会包含这个字段,无论你增,改,查都不会管这个字字段,所以读出来始终为空null值。下面介绍一种利用linq的变通的办法。
public class EmployeeVM{ public int EmployeeId { get; set; } public string EmployeeName { get; set; } public string CustomerName { get; set; }}
public List<Employee> GetEmployees(){ using (MyContext context = new MyContext()) { return context.Database.SqlQuery<EmployeeVM>("select E.EmployeeId, E.EmployeeName, C.CustomerName from Employee E left join Customer C on E.CustomerId = C.CustomerId") .Select(x=> new Employee(){ EmployeeId = x.EmployeeId, EmployeeName = x.EmployeeName, CustomerName = x.CustomerName }).ToList(); }}
https://www.lanhusoft.com/Article/247.html
阅读全文
0 0
- 解决EF使用context.Database.SqlQuery时NotMapped属性列为空null的问题
- context.Database.SqlQuery<>()查询
- MVC中EF中解决模型类NotMapped属性无效,即列名"xx"无效
- EF的SqlQuery和EntitySql
- 解决返回json数据,属性值为null或空被省略的问题。
- 解决在使用request得到属性的空指针问题
- 系统视图sys.databases的collation_name 列为 NULL的问题
- mysql列为null时排序
- SQL修改列为非空属性
- 某列为空时选择前面的非空值
- 解决Entity Framework(EF) 使用时,数据库结构对应,但EF还是提示要删除数据库的问题
- 解决Context.getExternalFilesDir(null)返回null造成java.lang.NullPointerException的问题
- 使用ALTER DATABASE解决sqlserver2000的问题
- ef 6中 notmapped 放在类上,对属性没影响
- SQLQUERY的使用
- mysql查询某列为空的数据
- 解决从相册获取图片路径cursor = getContentResolver().query(uri, proj, null, null, null)报空的问题
- Hibernate 使用Query、SQLQuery 的setCacheable()设置缓存问题
- 踏破铁鞋
- Redis sentinel 高可用主从配置方案
- Python xlrd和xlwt读写Excel
- 配置Freeswitch新增用户
- 原生js实现ajax
- 解决EF使用context.Database.SqlQuery时NotMapped属性列为空null的问题
- [RK3288][Android6.0] 调试笔记 --- 3GPP转成PCM格式
- FTP
- android高亮布局引导Hlight
- 梯度下降法及matlab实现
- https流程
- HTML5 autofocus属性
- The requested URL /api/v1 was not found on this server
- 类成员函数和函数返回值的结合使用探究