简体   繁体   中英

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:

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

Is it possible to use complex queries like above?

I use 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.

To check out the example below, you can use LinqPad and add your Entity Framework DLL by using EntitityFramework(ObjectContext) via Add connection. 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 . The result will be returned as 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:

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

The same example, but this time with EntityFramework (DbContext) :

Add your Entity Framework DLL by using EntitityFramework(DbContext V4/V5/V6) via Add connection. Specify connection properties (don't forget to specify the AppConfig file) and close the connection dialog. 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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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