SqlQuery放入[NotMapped]字段? [英] SqlQuery into a [NotMapped] field?

查看:43
本文介绍了SqlQuery放入[NotMapped]字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行良好的实体,但是随后我需要附加来自另一个表的其他属性.我没有制作视图的能力,所以我只想添加一个[NotMapped]的字段,然后使用Context.Database.SqlQuery执行我的自定义语句并返回所有普通字段和这个新字段.

I have an entity that is working great, but then I have a requirement to tack on an additional property that comes from another table. I don't have the ability to make a View, so I want to just add a field that is [NotMapped] then use the Context.Database.SqlQuery to execute my custom statement and return all the normal fields and this new field.

换句话说,是这样的:

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();
    }
}

是的,不是最好的例子,而是最简单的方法.从我一直阅读的所有内容来看,SqlQuery应该忽略属性,因此应该可以正常工作,但是我的CustomerName总是返回null(我在Management Studio中运行了SQL,它在那里有一个值,只是在EF反序列化之后才存在)进入我的对象).

Yes yes, not the best example, but the simplest way to get the point across. From everything I've been reading, SqlQuery is supposed to ignore attribute, so this should work, but my CustomerName is always coming back null (I've run the SQL in Management Studio, it has a value there, just not after EF deserializes into my objects).

要使它正常工作,我需要做什么?还是可以吗?EF是否已更改为不允许这样做?

What do I need to do to get this to work? Or can I? Was EF changed to not allow this?

-shnar

推荐答案

在使用存储过程对计算字段进行选择时,我遇到了同样的麻烦.我创建了一个视图模型,该视图模型完全类似于没有db批注的实体.然后,在使用视图模型调用存储过程之后,选择我的实体.因此,使用上面的示例:

I had the same trouble using stored procedures to do selects with calculated fields. I created a view model that looks exactly like my entity without the db annotations. Then after I call my stored procedure using the view model I select into my entity. So, using your example above:

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();
    }
}

希望这会有所帮助.

这篇关于SqlQuery放入[NotMapped]字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆