shn*_*nar 5 c# sql entity-framework
我有一个运作良好的实体,但是接下来我需要附加来自另一个表的其他属性。我没有制作视图的能力,所以我只想添加一个[NotMapped]的字段,然后使用Context.Database.SqlQuery执行我的自定义语句并返回所有普通字段和这个新字段。
换句话说,是这样的:
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
[NotMapped]
public string CustomerName { get; set; }
}
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();
}
}
Run Code Online (Sandbox Code Playgroud)
是的,不是最好的例子,而是最简单的方法。从我一直在阅读的所有内容来看,SqlQuery应该忽略属性,因此应该可以正常工作,但是我的CustomerName总是返回null(我在Management Studio中运行了SQL,它在那里有一个值,只是在EF反序列化之后没有)进入我的对象)。
我需要做什么才能使它正常工作?可以吗 EF是否已更改为不允许这样做?
-shnar
我在使用存储过程对计算字段进行选择时遇到了同样的问题。我创建了一个视图模型,它看起来与我的实体完全相同,没有数据库注释。然后,在我使用视图模型调用存储过程后,我选择进入我的实体。因此,使用上面的示例:
public class EmployeeVM
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string CustomerName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以调用:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。