Why Skip and Take does not work when passing through a method? - linq

Suppose following codes:
IEnumerable<MyClass> MakeQuery()
{
var query = from m in session.Linq<MyClass>()
select m;
return query;
}
List<MyClass> m1()
{
return MakeQuery()
.Skip(10)
.Take(20)
.ToList<MyClass>();
}
List<MyClass> m2()
{
var query = from m in session.Linq<MyClass>()
select m;
return query
.Skip(10)
.Take(20)
.ToList<MyClass>();
}
Supposing all queries are same, it seems that in m1(), Skip and Take does not work. Indeed its like they do not exist all.
Why this happens and how can be fixed?
I'm using linq-to-nhibernate and this methods are used for paging. Thanks.

Why not use IQueryable for the MakeQuery() method?
IQueryable<MyClass> MakeQuery()
{
return session.Linq<MyClass>();
}
Not that the actual query makes a lot of sense. But I'll leave that to you.
But this is also the only difference between m1() and m2()

Related

How to return the result set with columns with Linq

I have a function inside a class that will run a Linq to Entities query (or any type of Linq query actually), and it's gonna return 2 columns in the resultset. I would like to return an object to whoever is calling my function that will allow Intellisense to know what I have returned.
Let me explain. If I have a function like this:
public static IQueryable GetInfo(MyEntityModel oEntityModel)
{
var query =
(from t in oEntityModel.Table1
from u in t.Table2
where t.Status == true &&
u.Status == true
select new
{
t.Column1,
u.Column2
})
return query;
}
What can (should) I put instead of IQueryable so that whoever calls my GetInfo function, will get Intellisense from the resultset, and show that it has a Column1 and Column2?
var linqresult = ClsLinqTeste.GetInfo(oEntityModel);
if (linqresult.Column1 == 1)
{
foreach (var oItem in linqresult)
{
.. do stuff...
}
}
Tks
You cannot return an anonymous type from a function, they are strictly "inline" classes. When you return it, the foreach loop will only be able to interpret the result as an plain object. I guess you could use reflection to query the property names and values, however it seems much more straight forward to define a data transfer type to hold the results.
See this question, and this blog post.
So you could create a simple struct or class:
public class MyDataResult
{
public object Column1 { get; set; }
public object Column2 { get; set; }
}
Then modify your query in the function:
public static IQueryable<MyDataResult> GetInfo(MyEntityModel oEntityModel)
{
var query =
(from t in oEntityModel.Table1
from u in t.Table2
where t.Status == true &&
u.Status == true
select new MyDataResult
{
Column1 = t.Column1,
Column2 = u.Column2
})
return query;
}
Something like that should work. Note that I used "object" for the properties in MyDataResult. I don't know the types of the columns you are returning, you should use the actual types in order to get full intellisense.
You are returning a collection of anonymous types, they will be casted to objects, so when you try to iterate over them, altough they will be your objects (and they will contain your properties) at compile time they will be casted to objects:
foreach (var x in ClsLinqTeste.GetInfo(oEntityModel))
{
//x is an Object
}
You can read more about it here.
If you want to have intellisense, I suggest you create a custom class they will hold your properties and return not an anonymous type (using new {}) but object of your class (new MyClass(prop1, prop2)). You also need to change signature of your method, so it returns IQueryable<YourClass> and not just plain non-generic IQueryable.
As others have said, creating a new type to hold the two columns is usually the best option.
But if, for some reason, you don't want to do that and you are using .Net 4.0, you can use Tuple:
public static IQueryable<Tuple<Column1Type, Column2Type>>
GetInfo(MyEntityModel oEntityModel)
{
return from …
select Tuple.Create(t.Column1, u.Column2);
}
var linqresult = ClsLinqTeste.GetInfo(oEntityModel);
foreach (var oItem in linqresult)
Console.WriteLIne(oItem.Item1, oItem.Item2);
When you return your resultset AsQueryable, the app is already able to give you intellisense, however in your example, you must specify either .FirstOrDefault if you know your collection will only have a single row, or iterate over your collection to get the items from it, like so:
This is what you're doing:
var linqresult = ClsLinqTeste.GetInfo(oEntityModel);
if (linqresult.Column1 == 1)
{
..do stuff...
}
This is how you should do it:
var linqresult = ClsLinqTeste.GetInfo(oEntityModel);
foreach(var item in linqresult)
{
if (item.Column1 == 1)
{
..do stuff...
}
}
You must iterate over linqresult because when you query with link, it returns a result set, even if it just has one column. As with any collection, your data columns aren't available on the whole result set, only with individual items.
If you want to strongly typed enumerate a non-generic IEnumerable (IEnumerable.GetEnumerator() instead of IEnumerable<T>.GetEnumerator<T>()) you can use the Cast<>() extension, like so
var myquery = GetQueryable();
for (var item in myquery.Cast<MyDataType>())
{
// use item.Column1 directly and strongly typed with intellisense
}

compiling a linq to sql query

I have queries that are built like this:
public static List<MyObjectModel> GetData (int MyParam)
{
using (DataModel MyModelDC = new DataModel())
{ var MyQuery = from....
select MyObjectModel { ...}
}
return new List<MyObjectModel> (MyQuery)
}
}
It seems that using compiled linq-to-sql queries are about as fast as stored procedures and so the goal is to convert these queries into compiled queries. What's the syntax for this?
Thanks.
Put something like this inside of your DataContext (or in your case your "DataModel"):
private static Func<DataModel, int, MyObjectModel> _getObjectModelById =
CompiledQuery.Compile<DataModel, int, MyObjectModel>(
(dataModel, myParam) =>
dataModel.PersonDtos.where(c => c.ObjectModelId == myParam).FirstOrDefault()
);
Then add amethod in there to call it like this:
internal List<MyObjectModel> GetObjectModel(int myParam)
{
var results = _getObjectModelById(this, myParam);
return results.SingleOrDefault();
}
Inside of your repository where your original method was call the internal function to get the result you are looking for.
Hope this helps -> I can post more code if necessary :)

Nhibernate 3.0 LINQ: Problem returning to IQueryable (non generic version) - doesn't allow ToList()

I am using the latest Nhibernate and i have a linq query to return just 1 column. so I can't use for example IQueryable as there is no entity class - i am returning only 1 column. But return to IQueryable Non Generic version doesn't provide the ToList method
Here is the method
public IQueryable GetCode()
{
using (ITransaction transaction = _session.BeginTransaction())
{
var results = (from c in _session.Query<Client>()
select new
{
Group = c.Code
}).Distinct();
}
}
Of course if i do this (see below) i get the ToList method on my IQueryable
public IQueryable<Client> GetCode()
{
using (ITransaction transaction = _session.BeginTransaction())
{
var results = (from c in _session.Query<Client>()
select c;
}
}
The problem being is that i need to do DISTINCT and use only 1 column.
Any ideas, i am at a loss
Thanks in advance
EDIT
When i look at the type that is returned via IQueryable it is
{NHibernate.Linq.NhQueryable<<>f__AnonymousType6>}
and looking under the base class of what is returned i see an exception
Expression type 10005 is not supported by this SelectClauseVisitor.
Wouldn't the following work?
public IQueryable<X> GetCode() // X = the type of Client.Code
{
using (ITransaction transaction = _session.BeginTransaction())
{
var results = (from c in _session.Query<Client>()
select c.Code).Distinct();
}
}
The problem here is not just that you can't call ToList on a non-generic IQueryable, but that the entire result is untyped, so you cannot read the Code property of each element either. (This can be worked around with C# 4's dynamic type, but that's not really what you want here.)
In your case, I don't see why you really need to construct an anonymous type just to return a distinct sequence of Code values renamed as Group. Returning the field's value should be sufficient.
If you'd need to return more than just one column, you should create an explicit type, rather than using an anonymous type, so you can say
public IQueryable<ClientGroupAndSomething> GetCode()
{
using (ITransaction transaction = _session.BeginTransaction())
{
var results = (from c in _session.Query<Client>()
select new ClientGroupAndSomething
{
Group = c.Code,
...
}).Distinct();
}
}

Using NHibernate.Linq and getting 2 queries for a simple select, why?

so here's the code with irrelevant bits left out:
public IEnumerable<T> GetByQuery(Expression<Func<T, bool>> filter
{
try
{
return Session.Linq<T>().Where(filter);
}
catch(Exception ex)
{
// custom exception handling here
}
finally
{
CloseSession();
}
return null;
}
and an example of it being called looks like this:
IEnumerabl<ClientReport> clientReports =
clientReportRepository.GetByQuery(item => item.ClientId = id);
So as you can see, nothing fancy and being called in this way, we're hitting one table in the database with no relationships to any other tables. But when I have show_sql = true in the configuration, It's displaying 2 of the same query.
Any ideas?
Thanks
clientReports will probably execute the query every time you enumerate it (or get the Count(), for example).
To avoid that, use .ToList() in the assignment.

Linq2SQL "Local sequence cannot be used in LINQ to SQL" error

I have a piece of code which combines an in-memory list with some data held in a database. This works just fine in my unit tests (using a mocked Linq2SqlRepository which uses List).
public IRepository<OrderItem> orderItems { get; set; }
private List<OrderHeld> _releasedOrders = null;
private List<OrderHeld> releasedOrders
{
get
{
if (_releasedOrders == null)
{
_releasedOrders = new List<nOrderHeld>();
}
return _releasedOrders;
}
}
.....
public int GetReleasedCount(OrderItem orderItem)
{
int? total =
(
from item in orderItems.All
join releasedOrder in releasedOrders
on item.OrderID equals releasedOrder.OrderID
where item.ProductID == orderItem.ProductID
select new
{
item.Quantity,
}
).Sum(x => (int?)x.Quantity);
return total.HasValue ? total.Value : 0;
}
I am getting an error I don't really understand when I run it against a database.
Exception information:
Exception type: System.NotSupportedException
Exception message: Local sequence cannot be used in LINQ to SQL
implementation of query operators
except the Contains() operator.
What am I doing wrong?
I'm guessing it's to do with the fact that orderItems is on the database and releasedItems is in memory.
EDIT
I have changed my code based on the answers given (thanks all)
public int GetReleasedCount(OrderItem orderItem)
{
var releasedOrderIDs = releasedOrders.Select(x => x.OrderID);
int? total =
(
from item in orderItems.All
where releasedOrderIDs.Contains(item.OrderID)
&& item.ProductID == orderItem.ProductID
select new
{
item.Quantity,
}
).Sum(x => (int?)x.Quantity);
return total.HasValue ? total.Value : 0;
}
I'm guessing it's to do with the fact
that orderItems is on the database
and releasedItems is in memory.
You are correct, you can't join a table to a List using LINQ.
Take a look at this link:
http://flatlinerdoa.spaces.live.com/Blog/cns!17124D03A9A052B0!455.entry
He suggests using the Contains() method but you'll have to play around with it to see if it will work for your needs.
It looks like you need to formulate the db query first, because it can't create the correct SQL representation of the expression tree for objects that are in memory. It might be down to the join, so is it possible to get a value from the in-memory query that can be used as a simple primitive? For example using Contains() as the error suggests.
You unit tests work because your comparing a memory list to a memory list.
For memory list to database, you will either need to use the memoryVariable.Contains(...) or make the db call first and return a list(), so you can compare memory list to memory list as before. The 2nd option would return too much data, so your forced down the Contains() route.
public int GetReleasedCount(OrderItem orderItem)
{
int? total =
(
from item in orderItems.All
where item.ProductID == orderItem.ProductID
&& releasedOrders.Contains(item.OrderID)
select new
{
item.Quantity,
}
).Sum(x => (int?)x.Quantity);
return total.HasValue ? total.Value : 0;
}

Resources