简体   繁体   English

在EF中使用SQL查询

[英]Using sql queries in EF

I am getting data from database in following way: 我通过以下方式从数据库获取数据:

 result = (from d in context.FTDocuments
                          join f in context.FTDocFlags on d.ID equals f.DocID into fgrp
                          from x in fgrp.DefaultIfEmpty()
                          where d.LevelID == levelID && x.UserID == userID && d.Status.Equals(DocumentStatus.NEW)
                          select new Entities.Document
                          {
                              ArrivalDate = d.ArrivalDate.Value,
                              BundleReference = d.BundleRef,
                              CreatedDate = d.CreatedDate,
                              CustomerID = d.CustomerID,
                              DocType = d.DocType.Value,
                              GuidID = d.DocGuid,
                              ID = d.ID,
                              LastExportID = d.LastExpID,
                              LevelID = d.LevelID,
                              ProfileID = d.ProfileID,
                              ScanDate = d.ScanDate.Value,
                              ScanOperator = d.ScanOperator,
                              SenderEmail = d.SenderEmail,
                              Status = d.Status,
                              VerifyOperator = d.VerOperator,
                              FlagNo = x == null ? 0 : x.FlagNo,
                              FlagUserID = x == null ? 0 : x.UserID
                          }).ToList();

Now, I am try to achieve this by using sql queries: 现在,我尝试通过使用sql查询来实现这一点:

var test = context.Database.SqlQuery<string>("select *from FTDocument d left outer join FTDocFlag f on d.ID=f.DocID").ToList();

But get the following error: 但是出现以下错误:

The data reader has more than one field. 数据读取器具有多个字段。 Multiple fields are not valid for EDM primitive or enumeration types 多个字段对于EDM原语或枚举类型无效

Is it possible to use complex queries like above? 是否可以使用上述复杂查询?

I use EF 6.0. 我使用EF 6.0。

your query does not return a single string. 您的查询不返回单个字符串。 Use like: 使用方式如下:

var test = context.Database.SqlQuery<Entities.Document>("...");

try this 尝试这个

const string query = @"select *from FTDocument d left outer join FTDocFlag f on d.ID=f.DocID";

var test = context.Database.SqlQuery<Entity>(query).ToList();

In my answer I have assumed EntitityFramework (ObjectContext) first, but then I have added the code for DbContext as well. 在我的回答中,我首先假定了EntitityFramework(ObjectContext) ,但随后我还添加了DbContext的代码。

To check out the example below, you can use LinqPad and add your Entity Framework DLL by using EntitityFramework(ObjectContext) via Add connection. 要查看下面的示例,可以使用LinqPad并通过添加连接使用EntitityFramework(ObjectContext)添加实体框架DLL Specify connection properties and close the connection dialog. 指定连接属性并关闭连接对话框。 Then select the connection and run the example: 然后选择连接并运行示例:

void Main()
{
    var context=this; // requires that you selected an EF ObjectContext connection  
    var q=context.ExecuteStoreQuery<FTDocument>(
                                   "SELECT * FROM FTDocument WHERE ID = @p0", 1);
    q.ToList().Dump();
}

It will accept all kind of SQL queries, and you can use parameters like @p0 , @p1 etc and simply append them comma-separated when you invoke the function ExecuteStoreQuery . 它将接受所有类型的SQL查询,并且您可以使用@p0@p1等参数,并在调用ExecuteStoreQuery函数时将它们以逗号分隔即可。 The result will be returned as List<FTDocument> . 结果将作为List<FTDocument>返回。 To convert it to List<string> you need to specify which database field you want to return - or you create a comma-separated list of field values in each row, for example: 要将其转换为List<string>您需要指定要返回的数据库字段-或在每行中创建一个用逗号分隔的字段值列表,例如:

    q.Select(s=>s.ID+", "+s.GuidID+", "+s.DocType).ToList().Dump();

The same example, but this time with EntityFramework (DbContext) : 相同的示例,但是这次使用EntityFramework(DbContext)

Add your Entity Framework DLL by using EntitityFramework(DbContext V4/V5/V6) via Add connection. 通过添加连接使用EntitityFramework(DbContext V4 / V5 / V6)添加您的Entity Framework DLL Specify connection properties (don't forget to specify the AppConfig file) and close the connection dialog. 指定连接属性(不要忘记指定AppConfig文件)并关闭连接对话框。 Then select the connection and run the example: 然后选择连接并运行示例:

void Main()
{
    var context=this; // requires that you selected an EF DBContext (V4/5/6) connection 
    var q=context.Database.SqlQuery<FTDocument>(
                               "SELECT * FROM FTDocument WHERE ID = @p0", 1);
    q.ToList().Dump();
}

Tip: Before you close the connection dialog, click Test . 提示:关闭连接对话框之前,请单击“ 测试” It will save you a headache later if you know the connection succeeds. 如果您知道连接成功,将在以后减轻您的头痛。 For all those who want to try it out with a different EF project with your own database, here is a quick tutorial how to create it. 对于所有想要在具有您自己的数据库的其他EF项目中进行尝试的人, 这里有一个快速的教程如何创建它。 Then simply replace FTDocument in the example above by a different table of your choice (in the SQL string and inside the brackets <...> of course). 然后只需将上面示例中的FTDocument替换为您选择的其他表即可(当然,在SQL字符串和方括号<...>中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM