I'm using a Generic Repository like pattern to fetch data. There are 100+ entities so creating a separate repository for each is not really an option. here are a few functions from the same class:
public int Count(Func<TEntity, bool> x=null)
{
return x == null ?
mgr.CTX.GetAll<TEntity>().Count() :
mgr.CTX.GetAll<TEntity>().Where(x).Count();
}
public TEntity One(Func<TEntity, bool> x)
{
return mgr.CTX.GetAll<TEntity>().Where(x).Take(1).FirstOrDefault();
}
public IQueryable<TEntity> All(Func<TEntity, bool> x=null)
{
return x == null ?
mgr.CTX.GetAll<TEntity>() :
mgr.CTX.GetAll<TEntity>().Where(x).AsQueryable<TEntity>();
}
The problem is no matter which function is call, the Sql profiler shows the same
Select [columns] from [table]
I suppose when using Take(1) or Count() or Where() the query should be made accordingly using Count(), Top or Where clauses of Select but these functions have absolutely no effects on query generation. Apparently, every operation seems to be performed in memory after fetching all the data from server.
Guide me if there is something wrong with the way I'm accessing it or this is the normal behavior of telerik?
I believe you are victim of a subtle difference between definitions of LINQ extension method - in-memory ones use Func<> while SQL-bound use Expression<> as parameter type.
My suggestion is to change All(Func<TEntity, bool> x=null) to All(Expression<Func<TEntity, bool>> x=null)
Related
I'm running an EF statement where I need to calculate de deductibles. After long trying, I can't seem to add a custom function in a .Select() statement. Instead I'm trying to add the values after my .Select() statement.
The problem here is, in my CalculateDeductibles() I can't seem to add any values to item.Deductibles.
The GetDeductibles(item.RequestId) is a rather heavy funtion that does several extra queries, so I'm trying to prevent to convert my IQueryable to an IList object.
So there are actually 2 questions:
Can I have the GetDeductibles() function directly in my .Select() statement?
Can I somehow (with keeping an eye on performance) add the value after I did my .Select()
Code:
public IQueryable<ReinsuranceSlip> GetReinsuranceSlipsOverview(int userId, int companyId, string owner, string ownerCompany)
{
IQueryable<ReinsuranceSlip> model = null;
model = _context.Request
.Where(w => w.RequestGroup.ProgramData.MCContactId == userId)
.Select(x => new ReinsuranceSlip()
{
Id = x.Id,
RequestId = x.Id,
LocalPolicyNumber = x.LocalPolicyNumber,
BusinessLine = x.RequestGroup.ProgramData.BusinessLine.DisplayName,
BusinessLineId = x.RequestGroup.ProgramData.BusinessLine.Id,
ParentBroker = x.RequestGroup.ProgramData.Broker.Name,
LocalBroker = x.Broker.Name,
InceptionDate = x.InceptionDate,
RenewDate = x.RenewDate,
//Deductibles = CalculateDeductibles(x)
});
CalculateDeductibles(model);
return model;
}
private void CalculateDeductibles(IQueryable<ReinsuranceSlip> model)
{
//model.ForEach(m => m.Deductibles = GetDeductibles(m.RequestId));
foreach (var item in model)
{
item.Deductibles = GetDeductibles(item.RequestId);
}
}
Updated and Sorry for the first version of this answer. I didn't quite understand.
Answer 1: IQueryable is using to creating a complete SQL statement to call in SQL Server. So If you want to use IQueryable, your methods need to generate statements and return it. Your GetDetuctibles method get request Id argument but your queryable model object didn't collect any data from DB yet, and it didn't know x.Id value. Even more, your GetCarearDetuctiples get an argument so and with that argument generates a queryable object and after some calculations, it returns decimal. I mean yes you can use your methods in select statement but it's really complicated. You can use AsExpendable() LINQ method and re-write your methods return type Expression or Iqueryable.
For detailed info you should check. This:
Entity Navigation Property IQueryable cannot be translated into a store expression and this: http://www.albahari.com/nutshell/predicatebuilder.aspx
And you also should check this article to understand IQueryable interface: https://samueleresca.net/2015/03/the-difference-between-iqueryable-and-ienumerable/
Answer 2: You can use the IEnumerable interface instead IQueryable interface to achieve this. It will be easy to use in this case. You can make performance tests and improve your methods by time.
But if I were you, I'd consider using Stored Procedures for performance gain.
You'll have to understand the differences between an IEnumerable and an IQueryable.
An IEnumerable object holds everything to enumerate over the elements in the sequence that this object represents. You can ask for the first element, and once you've got it, you can repeatedly ask for the next element until there is no more next element.
An IQueryable works differently. An IQueryable holds an Expression and a Provider. The Expression is a generic description of what data should be selected. The Provider knows who has to execute the query (usually a database), and it knows how to translate the Expression into a format that the Provider understands.
There are two types of LINQ functions: the ones that return IQueryable<TResult> and the ones that return TResult. Functions form the first type do not execute the query, they will only change the expression. They use deferred execution. Functions of the second group will execute the query.
When the query must be executed, the Provider takes the Expression and tries to translate it into the format that the process that executes the query understand. If this process is a relational database management system this will usually be SQL.
This translation is the reason that you can't add your own functionality: the Expression must be translatable to SQL, and the only thing that your functions may do is call functions that will change the Expression to something that can be translated into SQL.
In fact, even entity framework does not support all LINQ functionalities. There is a list of Supported and Unsupported LINQ methods
Back to your questions
Can I have GetDeductibles directly in my query?
No you can't, unless you can make it thus simple that it will only change the Expression using only supporte LINQ methods. You'll have to write this in the format of an extension function. See extension methods demystified
Your GetDeductibles should have an IQueryable<TSource> as input, and return an IQueryable<TResult> as output:
static class QueryableExtensions
{
public static IQueryable<TResult> ToDeductibles<TSource, TResult, ...>(
this IQueryable<TSource> source,
... other input parameters, keySelectors, resultSelectors, etc)
{
IQueryable<TResult> result = source... // use only supported LINQ methods
return result;
}
}
If you really need to call other local functions, consider calling AsEnumerable just before calling the local functions. The advantage above ToList is that smart IQueryable providers, like the one in Entity Framework will not fetch all items but the items per page. So if you only need a few ones, you won't have transported all data to your local process. Make sure you throw away all data you don't need anymore before calling AsEnumerable, thus limiting the amount of transported data.
Can I somehow add the value after I did my .Select()
LINQ is meant to query data, not to change it. Before you can change the data you'll have to materialize it before changing it. In case of a database query, this means that you have a copy of the archived data, not the original. So if you make changes, you'll change the copies, not the originals.
When using entity framework, you'll have to fetch every item that you want to update / remove. Make sure you do not select values, but select the original items.
NOT:
var schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.Select(school = new
{
... // you get a copy of the values: fast, but not suitable for updates
})
.FirstOrDefault();
BUT:
School schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.FirstOrDefault()
Now your DbContext has the original School in its ChangeTracker. If you change the SchoolToUpdate, and call SaveChanges, your SchoolToUpdate is compared with the original School, to check if the School must be updated.
If you want, you can bypass this mechanism, by Attaching a new School directly to the ChangeTracker, or call a Stored procedure.
Consider a database with multiple tables built using Entity Framework code first. Each table contains a different type of object, but I wish to create a single generic query builder class for extensibility's sake. So far as a framework for this class I have a generic class as so intended to act as a wrapper for Linq to SQL:
public class DBQuerier<T>
where T : class
{
DbSet<T> relation;
public DBQuerier(DbSet<T> table)
{
relation = table;
}
public bool Exists(T toCheck);
public void Add(T toAdd);
public T (Get Dictionary<String, Object> fields);
public bool SubmitChanges();
public void Update(T toUpdate, Dictionary<String, Object> fields);
public void Delete(T toDelete);
}
My problem comes at the first hurdle when trying to check to see if a record exists as I cannot convert between generic type T and an object type that I am trying to work with. If I use base Linq:
public bool Exists(T toCheck)
{
return (from row in relation
where row.Equals(toCheck)
select row).Any();
}
A run-time exception occurs as SQL cannot work with anything but primitive types even if I implement IComparable and designate my own Equals that compares a single field. Lambda Expressions seem to come closer, but then I get problems again with SQL not being able to handle more than primitive types even though my understanding was that Expression.Equal forced it to use the class' comparable function:
public bool Exists(T toCheck)
{
ParameterExpression T1 = Expression.Parameter(typeof(myType), "T1");
ParameterExpression T2 = Expression.Parameter(typeof(myType), "T2");
BinaryExpression compare = Expression.Equal(T1, T2);
Func<T, T, bool> checker =
Expression.Lambda<Func<T, T, bool>>
(compare, new ParameterExpression[] { T1, T2 }).Compile();
return relation.Where(r => checker.Invoke(r, toCheck)).Any();
}
The expression tree was designed in mind so that later I could add a switch statement to build the query according to the type I was trying to look at.
My question is: Is there a much simpler / better way to do this (or fix what I've tried so far) as the only other options I can see are to write a class for each table (not as easy to extend) or check each record application side (potentially horrendously slow if you have to transfer the whole database!)? Apologies if I've made so very basic mistakes as I haven't worked with much of this for very long at all, thanks in advance!
Don't compile it. Func<T,bool> means "run this in memory" while Expression<Func<T,bool>> means "keep the logical idea of what this predicate is" which allows frameworks like entity framework to translate that into the query.
As a side note, I don't think that entity framework lets you do a.Equals(b) for querying, so you'll have to do a.Id == b.Id
Entity framework is unlikely to work with your custom linq, it's quite rigid in the commands that it supports. I am going to ramble a bit and it's pseudocode, but I found two solutions that worked for me.
I first used generics approach, where my generic database searcher would accept a Func<T, string> nameProperty to access the name I was going to query. EF has many overloads for accessing sets and properties so I could make this work, by passing in c => c.CatName and using that to access the property in a generic fashion. It was a bit messy though, so:
I later refactored this to use interfaces.
I have a function that performs a text search on any table/column you pass into the method.
I created an interface called INameSearchable which simply contains a property that will be the name property to search. I then extended my entity objects (they are partial classes) to implement INameSearchable. So I have an entity called Cat which has a CatName property. I used the interface to return CatName; as the Name property of the interface.
I can then create a generic Search method where T : INameSearchable and it will expose the Name property that my interface exposed. I then simply use that in my method to perform the query, eg. (Pseudocode from memory!)
doSearch(myContext.Cats);
and in the method
public IEnumerable<T> DoSearch<T>(IDbSet<T> mySet, string catName)
{
return mySet.Where(c => c.Name == catName);
}
And quite beautifully, it allows me to generically search anything.
I hope this helps.
If you want to use EntityFramework you have to use primitive types. The reasons is that your LINQ-expression is converted to a SQL-statement. SQL doesn't know anything about objects, IComparables, ...
If you don't need it to be in SQL, you first have to execute the query against SQL and then filter it in memory. You can do that with the methods you're currently using
I'm trying to do the following:
var query =
(from a in session.Query<A>()
where a.BasicSearch(searchString) == true
select a);
But it keeps giving me this exception "System.NotSupportedException"!
Any idea how to solve this?
It is not possible to use user-defined functions in a LINQ query. The NHibernate linq provider does not 'know' how to translate your function into SQL.
LINQ to NHibernate works by inspecting the LINQ expression that you provide at runtime, and translating what it finds in this expression tree into a regular SQL expression. Here's a good article to get some background on expression trees: http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx
You CAN reuse predicates like this in another way however, using the techniques discussed here. (I'm not sure if this works with NHibernate however.) IF it works it would look something like this:
// this could be a static method on class A
public static Expression<Func<A, bool>> BasicSearch(string criteria)
{
// this is just an example, of course
// NHibernate Linq will translate this to something like
// 'WHERE a.MyProperty LIKE '%#criteria%'
return a => criteria.Contains(a.MyProperty);
}
Usage:
from a in Session.Query<A>().Where(A.BasicSearch(criteria))
UPDATE: apparently there will be issues with NHibernate. See this blog post for a version that ought to work.
It is possible to call your own and SQL functions, but you have to make a wrapper for them so that NHibernate knows how to translate the C# to SQL.
Here's an example where I write an extension method to get access to SQL Server's NEWID() function. You would use the same techniques to get access to any other function on your database server, built-in or user-defined.
Some examples to extend NHibernate LINQ:
http://fabiomaulo.blogspot.se/2010/07/nhibernate-linq-provider-extension.html
https://nhibernate.jira.com/browse/NH-3301
Declare a BasicSearch extension method. Supposing your udf is on dbo:
using NHibernate.Linq;
...
public static class CustomLinqExtensions
{
[LinqExtensionMethod("dbo.BasicSearch")]
public static bool BasicSearch(this string searchField, string pattern)
{
// No need to implement it in .Net, unless you wish to call it
// outside IQueryable context too.
throw new NotImplementedException("This call should be translated " +
"to SQL and run db side, but it has been run with .Net runtime");
}
}
Then use it on your entities:
session.Query<A>()
.Where(a => a.SomeStringProperty.BasicSearch("yourPattern") == true);
Beware, trying to use it without referencing an entity in its usage will cause it to get evaluated with .Net runtime instead of getting it translated to SQL.
Adapt this BasicSearch example to whatever input types it has to handle. Your question was calling it directly on the entity, which does not allow your readers to know on how many columns and with which types it need to run.
I'm trying to implement a generic class that will interact with a generic repository, and all is fine except for when I have to deal with getting objects out of the repository.
I'm going to have a virtual method in the generic class which will receive an int and I want to use that int to form a query to the repository that gets objects by their primary key. I have a feeling I need to work with the EntityKey property in EF, but not too sure how.
Anyway, here's what I'm trying to do in code, I hope someone will have suggestions on how to accomplish what I want:
public virtual T Get(int PrimaryKey) {
this.Repository.Select(
t =>
(t.PRIMARYKEY == PrimaryKey)).Single();
}
I want to extend this class with more specialized classes, but since most of them only get their objects by querying the PK, it makes since to me to have a base method that can do it.
Thanks in advance for any suggestions!
UPDATE
So, here's where I've gotten with reflection, and I doubt its the proper way, but it somewhat works... I'm getting a NotSupportedException with the message LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression.. Although I understand what it says and why it's saying, I'm not sure how to overcome it when my code looks like this:
private readonly string TEntityName = typeof(T).Name;
public virtual T Get(
int PrimaryKey) {
return this.Repository.Select(
t =>
(((int)t.GetType().GetProperties().Single(
p =>
(p.Name == (this.TEntityName + "Id"))).GetValue(t, null)) == PrimaryKey)).Single();
}
Hoping that someone who knows how to use reflection, unlike me, can point me in the right direction. Thanks!
Retrieving an entity by a PK using EF requires an expression/predicate, like this:
Expression<Func<Order,bool>> predicate = x => x.OrderId == 1;
return ctx.Orders.Single(predicate);
There is no easy way (short of reflection or expression tree creation) to be able to dynamically create this predicate.
What you could do is accept the predicate as a parameter:
public virtual T Get(Expression<Func<T,bool>> predicate) {
this.Repository.Select(predicate).Single();
}
Also make sure you put some generic constraints on T (either at the class/method level).
http://msdn.microsoft.com/en-us/library/bb738961.aspx is way to go. Then use http://msdn.microsoft.com/en-us/library/bb738607.aspx, spend some time in debugger and your misson is completed.
I have a class which provides generic access to LINQ to SQL entities, for example:
class LinqProvider<T> //where T is a L2S entity class
{
DataContext context;
public virtual IEnumerable<T> GetAll()
{
return context.GetTable<T>();
}
public virtual T Single(Func<T, bool> condition)
{
return context.GetTable<T>().SingleOrDefault(condition);
}
}
From the front end, both of these methods appear to work as you would expect. However, when I run a trace in SQL profiler, the Single method is executing what amounts to a SELECT * FROM [Table], and then returning the single entity that meets the given condition. Obviously this is inefficient, and is being caused by GetTable() returning all rows.
My question is, how do I get the query executed by the Single() method to take the form SELECT * FROM [Table] WHERE [condition], rather than selecting all rows then filtering out all but one? Is it possible in this context?
Any help appreciated.
Replace Func<...> with Expression<Func<...>>.