I would like to be able to use custom string querying within my NHibernate Linq expressions. Let's say for example (and this is just an example) I would like to be able to select entities containing a property which is an anagram of a particular string:
var myEntities = EntityRepository.AllEntities.Where(x => x.Description.IsAnagramOf('hits');
I imagine the steps involved in this process would be:
Define a SQL Server UDF to determine
whether two strings are anagrams.
Define an extension method called
IsAnagramOf() for the String
class.
(And this is the tricky one). Modify
Linq to NHibernate's
component for parsing expression
trees so that it converts calls to
the extension method into the
appropriate SQL UDF call.
My question is this. Does Linq to NHibernate contain some kind of extensibility model enabling me to 'slot in' my own custom string operations, or would I literally have to modify the existing source code to add in my shiznit to the expression tree parsing component?
The extensibility is built in NH 3.0 (final release next month).
You can see a full working example at http://fabiomaulo.blogspot.com/2010/07/nhibernate-linq-provider-extension.html
Related
I have a compiled assembly that contains a lot of my business logic rules which I would like to use inside of LINQ Pad. I can add a reference to the assembly using Query -> Query Properties, but once I have the reference how do I access the context?
My BL object expects an IMyDataSource object, not an individual IDbSet.
Normally in a LINQ Pad query, the individual DB sets are "magically" available via their names. For example
In normal .NET code I would write
Dim items As IQueryable(of Item) = DataSource.Items
but in LINQ Pad I would write it without a reference to the context.
Dim items = Items
Your LINQPad query is compiled into a sub-class of the Data Context, so your data source is available as Me. Therefor you can quality Items to Me.Items for the same result.
If you are using C# inside LINQPad, you can refer to the Data Context as simply this. For example, you can refer to the entity collection Items as this.Items and get the same results.
I use in my project a lot of LINQ queries and business methods.
To allow these business method to be used from an Iqueryable :
I defined UDF functions in SQL Server (with the needed parameters)
Add this UDF to the EDMX model of the application
And make a gateway between UDF and LinQ with a method like this in a
partial class who inherits from the dbcontext :
[EdmFunction("MyProject.Store", "GetTaxesOfProduct")]
public static Decimal GetTaxesOfProduct(Decimal amount, Int32 TaxMethod)
{
throw new NotSupportedException("Not direct access possible, use with E-SQL or LINQ");
}
This works perfectly for IQueryable.
But the problem is that, to use this method from a simple object (not linked to a database record), i need to make something creepy like this :
var query = from foo in context.JustATable select context.GetTaxesOfProduct(15.55, 3);
And recently i came across this http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx who explain how, with expression, you can make a method who is usable from C# objects and IQueryable
So, with expression, is it possible to make business methods like my method but without the use of UDF and just expressions ?
Thank you by advance !
It depends on the content of your UDF. Expression can work only with entities defined in your model and use only operations provided by Entity Framework provider for your database. So if you use any complex SQL statement with not supported equivalent for LINQ or non mapped features inside your UDF it will not work.
I have defined a GenericRepository class which does the db interaction.
protected GenericRepository rep = new GenericRepository();
And in my BLL classes, I can query the db like:
public List<Album> GetVisibleAlbums(int accessLevel)
{
return rep.Find<Album>(a => a.AccessLevel.BinaryAnd(accessLevel)).ToList();
}
BinaryAnd is an extension method which checks two int values bit by bit. e.g. AccessLevel=5 => AccessLevel.BinaryAnd(5) and AccessLevel.binaryAnd(1) both return true.
However I cannot use this extension method in my LINQ queries. I get a runtime error as follows:
LINQ to Entities does not recognize the method 'Boolean BinaryAnd(System.Object, System.Object)' method, and this method cannot be translated into a store expression.
Also tried changing it to a custom method but no luck. What are the workarounds?
Should I get all the albums and then iterate them through a foreach loop and pick those which match the AccessLevels?
I realize this already has an accepted answer, I just thought I'd post this in case someone wanted to try writing a LINQ expression interceptor.
So... here is what I did to make translatable custom extension methods: Code Sample
I don't believe this to be a finished solution, but it should hopefully provide a good starting point for anyone brave enough to see it through to completion.
You can only use the core extension methods and CLR methods defined for your EF provider when using Entity Framework and queries on IQueryable<T>. This is because the query is translated directly to SQL code and run on the server.
You can stream the entire collection (using .ToEnumerable()) then query this locally, or convert this to a method that is translatable directly to SQL by your provider.
That being said, basic bitwise operations are supported:
The bitwise AND, OR, NOT, and XOR operators are also mapped to canonical functions when the operand is a numeric type.
So, if you rewrite this to not use a method, and just do the bitwise operation on the value directly, it should work as needed. Try something like the following:
public List<Album> GetVisibleAlbums(int accessLevel)
{
return rep.Find<Album>(a => (a.AccessLevel & accessLevel > 0)).ToList();
}
(I'm not sure exactly how your current extension method works - the above would check to see if any of the flags come back true, which seems to match your statement...)
There are ways to change the linq query just before EF translates it to SQL, at that moment you'd have to translate your ''foreign'' method into a construct translatable by EF.
See an previous question of mine How to wrap Entity Framework to intercept the LINQ expression just before execution? and mine EFWrappableFields extension which does just this for wrapped fields.
I have a semi complicated question regarding Entity Framework4, Lambda expressions, and Data Transfer Objects (DTO).
So I have a small EF4 project, and following established OO principles, I have a DTO to provide a layer of abstraction between the data consumers (GUI) and the data model.
VideoDTO = DTO with getters/setters, used by the GUI
VideoEntity = Entity generated by EF4
My question revolves around the use of the DTO by the GUI (and not having the GUI use the Entity at all), combined with a need to pass a lambda to the data layer. My data layer is a basic repository pattern with Add. Change, Delete, Get, GetList, etc.
Trying to implement a Find method with a signature like so:
public IEnumerable<VideoDTO> Find(Expression<Func<VideoEntity, bool>> exp)
...
_dataModel.Videos.Where(exp).ToList<Video>()
---
My problem/concern is the "exp" needing to be of type VideoEntity instead of VideoDTO. I want to preserve the separation of concerns so that the GUI does not know about the Entity objects. But if I try to pass in
Func<VideoDTO, bool>
I cannot then do a LINQ Where on that expression using the actual data model.
Is there a way to convert a Func<VideoDTO,bool> to a Func<VideoEntity, bool>
Ideally my method signature would accept Func<VideoDTO, bool> and that way the GUI would have no reference to the underlying data entity.
Is this clear enough? Thanks for your help
Thanks for the repliesto both of you.
I'll try the idea of defining the search criteria in an object and using that in the LINQ expression. Just starting out with both EF4 and L2S, using this as a learning project.
Thanks again!
In architectures like CQRS there isn't need for such a conversion at all cause read & write sides of app are separated.
But in Your case, You can't runaway from translation.
First of all - You should be more specific when defining repositories. Repository signature is thing You want to keep explicit instead of generic.
Common example to show this idea - can You tell what indexes You need in Your database when You look at Your repository signature (maybe looking at repository implementation, but certainly w/o looking at client code)? You can't. Cause it's too generic and client side can search by anything.
In Your example it's a bit better cause expression genericness is tied with dto instead of entity.
This is what I do (using NHibernate.Linq, but the idea remains)
public class Application{
public Project Project {get;set;}
}
public class ApplicationRepository{
public IEnumerable<Application> Search(SearchCriteria inp){
var c=Session.Linq<Application>();
var q=c.AsQueryable();
if(!string.IsNullOrEmpty(inp.Acronym))
q=q.Where(a=>a.Project.Acronym.Contains(inp.Acronym));
/*~20 lines of similar code snipped*/
return q.AsQueryable();
}
}
//used by client
public class SearchCriteria{
public string Acronym{get;set;}
/*some more fields that defines how we can search Applications*/
}
If You do want to keep Your expressions, one way would be to define dictionary manually like this:
var d=new Dictionary<Expression<Func<VideoDTO,object>>,
Expression<Func<VideoEntity,object>>{
{x=>x.DtoPropNumberOne,x=>x.EntityPropNumberOne} /*, {2}, {3}, etc.*/
};
And use it later:
//can You spot it?
//client does not know explicitly what expressions dictionary contains
_dataModel.Videos.Where(d[exp]).ToList<Video>();
//and I'm not 100% sure checking expression equality would actually work
If You don't want to write mapping dictionary manually, You will need some advanced techniques. One idea would be to translate dto expression to string and then back to entity expression. Here are some ideas (sorting related though) that might help. Expressions are quite complicated beasts.
Anyway - as I said, You should avoid this. Otherwise - You will produce really fragile code.
Perhaps your design goal is to prevent propagation of the data model entities to the client tier rather than to prevent a dependency between the presentation layer and data model. If viewed that way then there would be nothing wrong with the query being formed the way you state.
To go further you could expose the searchable fields from VideoEntity via an interface (IVideoEntityQueryFields) and use that as the type in the expression.
If you don't want to add an interface to your entities then the more complicated option is to use a VideoEntityQuery object and something that translates an Expression<Func<VideoEntityQuery,bool>> to an Expression<Func<VideoEntity,bool>>.
Wikipedia states that the Specification Pattern is where business logic can be recombined by chaining the business logic together using boolean logic. With respect to selecting filtering objects from lists or collections it seems to me that Dynamic LINQ allows me to accomplish the same thing. Am I missing something? Are there other benefits to the Specification Pattern that should be considered as well?
Edit:
I've found some posts that discuss combining LINQ and the Specification Pattern:
Linq Specifications Project
Implementing the Specification Pattern via Linq by Nicloas Blumhardt (Autofac dude)
Has anyone gone done this road and did it become complicated to maintain?
I'm a C# developper and like to use the specification pattern, because it is closer of my business domain. Moreover, you don't have any surprise with this pattern, if a specification class exists, it should work. With Linq, your underlying provider maybe hasn't implemented some features, and you won't know it until runtime.
But definitively, the biggest advantage of specification over linq is to be closer to the business, it's a mini DSL. LINQ for me is a DSL for collection query, not for the business domain.
LINQ:
var oldMans = Persons.Where(x => x.Sex == SexEnum.Masculine && x.Age > 60).ToList();
Specification:
var oldMans = Persons.Where(x => IsOldManSpecification(x)).ToList();
The business logic is encapsuled in the specification (with a name that reveal what it is).
DRY: you don't repeat that linq over the code, you just use the Specification
I like to use specification when I think that the rule is important enough to be explicit in the code and it doesn't belongs naturally to the entity.
Example:
public class Customer
{
//...
public bool IsAbleToReceiveCredit(decimal creditValue)
{
var secureAge = this.Age > 18 && this.Age < 60;
var personalAssetsGreaterThanCreditValue = this.PersonalAssets.Sum(x => x.Value) > creditValue;
return secureAge && personalAssetsGreaterThanCreditValue;
}
}
Is it from the Customer the responsability to decide if he is able to receive some credit? A bank would ask to the customer if he can receive a loan?
Probably not.
So with specification you can remove that logic from the Customer (it never belonged to it). You can create something like IsAbleToReceiveCreditSpecification and put all logic there. We can go further and combine specifications, for example: you could create a SecureAgeSpecification and a AssetsGreaterThanSpecification and use them to compose the IsAbleToReceiveCreditSpecification.
So I don't think LINQ replaces the Specification. In fact it improves the pattern. There are some implementations of Specification that use LINQ internally with IQueriable<T>, with this you can use the specification inside your ORM queries on the Repository/DataAcess level.
Dynamic LINQ uses string expressions to allow the dynamic query construction. So we do in fact lose the type safety there. Whereas using wrapper patterns like the decorator pattern of it closely related incarnation, the specification pattern, allows us to maintain the type safety in code. I explore using the Decorator Pattern as query wrapper in order to reuse and dynamically build queries. You can find the article on code project at:
Linq Query Wrappers
Or you can check my blog.
I don't know LINQ really, but it seems to me that a declarative query system in general is related to the specification pattern. In particular, implementing a declarative query system by composing objects together in an object-oriented environment. IIRC that's akin to what LINQ does, providing a layer of syntactic sugar.
Whether LINQ completely obsoletes the pattern, I can't tell. Maybe there are corner cases that just can't be expressed in LINQ?