IQueryable<T> to raw SQL in Entity Framework - sql

How can I get the raw SQL generated against the below query in EF 6? I have tried ToString(), ToTraceString() but those are not working and I don't have access to the DbContext object at this point.
IQueryable<AccountApplication> query = AppService.QueryService.GetQueryMatching(spec);
var acccounts = (from a in query
where a.ApplicationId == applicationId && a.Id != 3
select new AccountDto
{
Id = a.Id,
Name = a.Account.AccountName,
ApplicationName = a.Application.ApplicationName,
SubsidaryId = a.Account.SubsidaryId.HasValue ? a.Account.SubsidaryId.Value : 0
}).ToList();

Did you try this
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query).ToTraceString();

Related

How to retrieve data from database using linq?

Is this a correct way of retreiving data from database using linq?
var c= using db in db.c where c.id==id
Is this a correct way of retreiving data from database using linq?
partially yes.
It's better to write your query inside a method like this:
public static Product GetProduct(int id, string name)
{
DBNameDataContext myDB = new DBNameDataContext();
var product = from p in myDB.Products
where p.ID == id
&& p.Name == name
select p;
return product;
}
and then in your main code you can get your Product as below:
var product = GetProduct(5, "C# in Depth");
(Sample code is in C#)

How can I select data with linq to sql from another query?

How can I select data with such linq to sql code, it's something wrong, i must compare WHERE, from st1 and st2, but something wrong. Also spaller didn't light this variables in where
var st1 = (from a in db.RouteDetail
where a.Station == "Гродно"
select new
{
a.Route,
});
var st2 = (from c in db.RouteDetail
where c.Station == "Лида"
select new
{
c.Route,
});
var res = (from d in db.RouteDetail
where st1.Route == st2.Route
select d);
Help me to do this, please.
I think what you mean to do is something like this :
var st1 = (from a in db.RouteDetail
where a.Station == "Гродно"
select new
{
a.Route,
});
var st2 = (from c in db.RouteDetail
where c.Station == "Лида"
select new
{
c.Route,
});
Both st1 and st2 now contain IQueryable types which allow you to enumerate over them. I'm assuming that your two queries only return one result in which case:
var station1 = st1.FirstorDefault();
var station2 = st2.FirstorDefault();
var res = (from d in db.RouteDetail
where station1.Route == station2.Route
select d);
Will do what you need it to do (provided they return a result theres no safety here for null exceptions). If however there is more than one result, it will only return the first match. In which case you will need to work out all the possible compositions from the values in st1 and st2

How do I map lists of nested objects with Dapper

I'm currently using Entity Framework for my db access but want to have a look at Dapper. I have classes like this:
public class Course{
public string Title{get;set;}
public IList<Location> Locations {get;set;}
...
}
public class Location{
public string Name {get;set;}
...
}
So one course can be taught at several locations. Entity Framework does the mapping for me so my Course object is populated with a list of locations. How would I go about this with Dapper, is it even possible or do I have to do it in several query steps?
Alternatively, you can use one query with a lookup:
var lookup = new Dictionary<int, Course>();
conn.Query<Course, Location, Course>(#"
SELECT c.*, l.*
FROM Course c
INNER JOIN Location l ON c.LocationId = l.Id
", (c, l) => {
Course course;
if (!lookup.TryGetValue(c.Id, out course))
lookup.Add(c.Id, course = c);
if (course.Locations == null)
course.Locations = new List<Location>();
course.Locations.Add(l); /* Add locations to course */
return course;
}).AsQueryable();
var resultList = lookup.Values;
See here https://www.tritac.com/blog/dappernet-by-example/
Dapper is not a full blown ORM it does not handle magic generation of queries and such.
For your particular example the following would probably work:
Grab the courses:
var courses = cnn.Query<Course>("select * from Courses where Category = 1 Order by CreationDate");
Grab the relevant mapping:
var mappings = cnn.Query<CourseLocation>(
"select * from CourseLocations where CourseId in #Ids",
new {Ids = courses.Select(c => c.Id).Distinct()});
Grab the relevant locations
var locations = cnn.Query<Location>(
"select * from Locations where Id in #Ids",
new {Ids = mappings.Select(m => m.LocationId).Distinct()}
);
Map it all up
Leaving this to the reader, you create a few maps and iterate through your courses populating with the locations.
Caveat the in trick will work if you have less than 2100 lookups (Sql Server), if you have more you probably want to amend the query to select * from CourseLocations where CourseId in (select Id from Courses ... ) if that is the case you may as well yank all the results in one go using QueryMultiple
No need for lookup Dictionary
var coursesWithLocations =
conn.Query<Course, Location, Course>(#"
SELECT c.*, l.*
FROM Course c
INNER JOIN Location l ON c.LocationId = l.Id
", (course, location) => {
course.Locations = course.Locations ?? new List<Location>();
course.Locations.Add(location);
return course;
}).AsQueryable();
I know I'm really late to this, but there is another option. You can use QueryMultiple here. Something like this:
var results = cnn.QueryMultiple(#"
SELECT *
FROM Courses
WHERE Category = 1
ORDER BY CreationDate
;
SELECT A.*
,B.CourseId
FROM Locations A
INNER JOIN CourseLocations B
ON A.LocationId = B.LocationId
INNER JOIN Course C
ON B.CourseId = B.CourseId
AND C.Category = 1
");
var courses = results.Read<Course>();
var locations = results.Read<Location>(); //(Location will have that extra CourseId on it for the next part)
foreach (var course in courses) {
course.Locations = locations.Where(a => a.CourseId == course.CourseId).ToList();
}
Sorry to be late to the party (like always). For me, it's easier to use a Dictionary, like Jeroen K did, in terms of performance and readability. Also, to avoid header multiplication across locations, I use Distinct() to remove potential dups:
string query = #"SELECT c.*, l.*
FROM Course c
INNER JOIN Location l ON c.LocationId = l.Id";
using (SqlConnection conn = DB.getConnection())
{
conn.Open();
var courseDictionary = new Dictionary<Guid, Course>();
var list = conn.Query<Course, Location, Course>(
query,
(course, location) =>
{
if (!courseDictionary.TryGetValue(course.Id, out Course courseEntry))
{
courseEntry = course;
courseEntry.Locations = courseEntry.Locations ?? new List<Location>();
courseDictionary.Add(courseEntry.Id, courseEntry);
}
courseEntry.Locations.Add(location);
return courseEntry;
},
splitOn: "Id")
.Distinct()
.ToList();
return list;
}
Something is missing. If you do not specify each field from Locations in the SQL query, the object Location cannot be filled. Take a look:
var lookup = new Dictionary<int, Course>()
conn.Query<Course, Location, Course>(#"
SELECT c.*, l.Name, l.otherField, l.secondField
FROM Course c
INNER JOIN Location l ON c.LocationId = l.Id
", (c, l) => {
Course course;
if (!lookup.TryGetValue(c.Id, out course)) {
lookup.Add(c.Id, course = c);
}
if (course.Locations == null)
course.Locations = new List<Location>();
course.Locations.Add(a);
return course;
},
).AsQueryable();
var resultList = lookup.Values;
Using l.* in the query, I had the list of locations but without data.
Not sure if anybody needs it, but I have dynamic version of it without Model for quick & flexible coding.
var lookup = new Dictionary<int, dynamic>();
conn.Query<dynamic, dynamic, dynamic>(#"
SELECT A.*, B.*
FROM Client A
INNER JOIN Instance B ON A.ClientID = B.ClientID
", (A, B) => {
// If dict has no key, allocate new obj
// with another level of array
if (!lookup.ContainsKey(A.ClientID)) {
lookup[A.ClientID] = new {
ClientID = A.ClientID,
ClientName = A.Name,
Instances = new List<dynamic>()
};
}
// Add each instance
lookup[A.ClientID].Instances.Add(new {
InstanceName = B.Name,
BaseURL = B.BaseURL,
WebAppPath = B.WebAppPath
});
return lookup[A.ClientID];
}, splitOn: "ClientID,InstanceID").AsQueryable();
var resultList = lookup.Values;
return resultList;
There is another approach using the JSON result. Even though the accepted answer and others are well explained, I just thought about an another approach to get the result.
Create a stored procedure or a select qry to return the result in json format. then Deserialize the the result object to required class format. please go through the sample code.
using (var db = connection.OpenConnection())
{
var results = await db.QueryAsync("your_sp_name",..);
var result = results.FirstOrDefault();
string Json = result?.your_result_json_row;
if (!string.IsNullOrEmpty(Json))
{
List<Course> Courses= JsonConvert.DeserializeObject<List<Course>>(Json);
}
//map to your custom class and dto then return the result
}
This is an another thought process. Please review the same.

NHibernate query count

I am new to NHibernate and I want to have a count of rows from database. Below is my code,
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
int count = template.Criteria.SetProjection(Projections.Count("ID"));
It gives me an error when I try to compile app that says
"Cannot implicitly convert type 'NHibernate.Criterion.DetachedCriteria' to 'int'"
I want to have a count of rows of the table hotel..
You want to use GetExecutableCriteria:
SearchTemplate template = new SearchTemplate();
template.Criteria = DetachedCriteria.For(typeof(hotel));
template.Criteria.Add(Restrictions.Lt("CheckOutDate", SelDate) || Restrictions.Eq("CheckOutDate", SelDate));
template.Criteria.Add(Restrictions.Eq("Canceled", "False"));
var count = DoCount(template.Criteria, session /* your session */);
public long DoCount(DetachedCriteria criteria, ISession session)
{
return Convert.ToInt64(criteria.GetExecutableCriteria(session)
.SetProjection(Projections.RowCountInt64())
.UniqueResult());
}
On a side note, you should take a look at using NHibernate.Linq:
var result = (from h in Session.Linq<Hotel>()
where h.CheckOutDate <= SelDate
where h.Canceled != true
select h).Count();
More information here.

nhibernate hql with named parameter

I have implemented a search function using Castel Active Record. I thought the code is simple enough but I kept getting
NHibernate.QueryParameterException : could not locate named parameter [searchKeyWords]
errors. Can someone tell me what went wrong? Thanks a million.
public List<Seller> GetSellersWithEmail(string searchKeyWords)
{
if (string.IsNullOrEmpty(searchKeyWords))
{
return new List<Seller>();
}
string hql = #"select distinct s
from Seller s
where s.Deleted = false
and ( s.Email like '%:searchKeyWords%')";
SimpleQuery<Seller> q = new SimpleQuery<Seller>(hql);
q.SetParameter("searchKeyWords", searchKeyWords);
return q.Execute().ToList();
}
Why do not u pass the % character with parameter?
string hql = #"select distinct s
from Seller s
where s.Deleted = false
and ( s.Email like :searchKeyWords)";
SimpleQuery<Seller> q = new SimpleQuery<Seller>(hql);
q.SetParameter("searchKeyWords", "%"+searchKeyWords+"%");
return q.Execute().ToList();