在实体框架使用SqlQuery类原始查询返回匿名类型 [英] Return Anonymous Type using SqlQuery RAW Query in Entity Framework

查看:687
本文介绍了在实体框架使用SqlQuery类原始查询返回匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能使实体框架类SqlQuery返回一个匿名类型。



现在我运行一个 context.TheObject.SqlQuery() RAW查询。在查询连接两个表,我想返回连接表的结果。



如果我用一个类型使用 context.TheObject.SqlQuery ()我只得到地看到,同类型的表的结果。



我试过 db.Database .SqlQuery<&DBRESULTS GT(SQL查询这里);与预先定义的类相匹配的结果的对象,但所有字段为空。



使用实体框架6与MySQL。


< DIV CLASS =h2_lin>解决方案

我的肢体会在这里,而且会尽量满足您的根本问题,而不是直接回答你的问题。



您与预先定义的类别场景的应该工作的。一个可能的缺陷是,列名和类的属性不匹配。



示例代码(LinqPad)

  VAR的结果= Database.SqlQuery<&的TestResult GT(从关系R选择r.Name,b.BankName内部联接的BankAccount b关于b.RelationId = r.Id其中r。 ID = 2); 
results.Dump();
}

公共类的TestResult {
公共字符串名称{;组; }
公共字符串BANKNAME {搞定;组; }



我强烈建议你使用显式类型重新审视你的问题的代码。






在你的问题直接回应:不,你不能从SqlQuery类返回匿名类型。你能做的最好的是建立的动态对象的,但是,不幸的是,需要使用TypeBuilder体力劳动公平一点。请参见 http://www.codeproject.com/文章/ 206416 /使用动态型在实体框架,类SqlQuery 一个样本。


How can I make Entity Framework SqlQuery to return an Anonymous type.

Right now I run a context.TheObject.SqlQuery() RAW query. the query joins two tables and I want to return the results of the joined tables.

If I use it with a type context.TheObject.SqlQuery() I only get to see the results of the table of that same type.

I tried db.Database.SqlQuery<DbResults>("the sql query here"); With a pre-defined class that matches the result's objects, but all the fields are null.

Using Entity Framework 6 with MySQL.

解决方案

I'm going out on a limb here, and will try to address your underlying problem instead of directly answering your question.

Your scenario with the pre-defined class should work. A likely pitfall is that the column names and the properties of your class did not match up.

Sample code (LinqPad)

    var results = Database.SqlQuery<TestResult>("select r.Name, b.BankName from relation r inner join BankAccount b on b.RelationId = r.Id where r.Id = 2");
    results.Dump();
}

public class TestResult {
    public string Name { get; set; }
    public string BankName { get; set; }

I'd strongly advise you to revisit your problematic code using explicit types.


In direct response to your question: no, you can't return anonymous types from SqlQuery. The best you can do is build dynamic objects, but that unfortunately requires a fair bit of manual work using TypeBuilder. See http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-SqlQuery for a sample.

这篇关于在实体框架使用SqlQuery类原始查询返回匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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