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.
Entity Framework allows you to execute raw SQL queries for the underlying relational database.
SQL Query for a specific entity type We can use SQLQuery() method to write SQL queries which return an entity object. Example: //DbContext. DbPersonnesEntities db = new DbPersonnesEntities();
Entity Framework Core allows you to drop down to raw SQL queries when working with a relational database. Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query.
Generally speaking, Entity Framework uses LINQ-to-Entities parametrized queries, and it is not susceptible to traditional SQL Injection attacks. However, Entity Framework does allow for the use of raw SQL queries when working with a relational database, introducing the risk of writing injectable queries.
your query does not return a single string. Use like:
var test = context.Database.SqlQuery<Entities.Document>("...");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With