Dynamic Linq query on relationship with foreign key of type Guid

c# dynamic-linq expression-trees sql

Question

I'm using System.Linq.Dynamic to dynamically query an IQueryable datasource with a string-formatted where-clause like this:

var result = source.Entities.Where("City = @0", new object[] { "London" });

The previous illustration is valid. But for now, I want to run the following query on a foreign key property of type Guid:

var result = source.Entities.Where("CompanyId = @0", new object[] { "838AD581-CEAB-4B44-850F-D05AB3D791AB" });

A Guid cannot by default be compared to a string, hence this won't work. Additionally, because the guid was originally part of a json-request and json does not handle guids, I must provide it as a string.

First off, is this even the proper syntax for querying across a relationship, or is there another?

How can I change Dynamic.cs from the Dynamic Linq project so that it automatically converts a string to a guid if the entity attribute being compared with is a guid?

1
1
2/8/2014 3:02:17 PM

Accepted Answer

You have a lot of options for solutions. I believe changing your question to be the easiest.

var result = source.Entities.Where("CompanyId.Equals(@0)", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });

When using operators,= and == next inDynamic.cs You must alter.interface IEqualitySignatures : IRelationalSignatures like as

interface IEqualitySignatures : IRelationalSignatures
{
    ....
    F(Guid x, Guid y);
    ....
}

then you may use the following question.

var result = source.Entities.Where("CompanyId=@0", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });

OR

var result = source.Entities.Where("CompanyId==@0", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });

Though if you want to utilizestring parameter has to be changedParseComparison approach inExpressionParser class. For operand kinds like these, you must add even more checking.

....
//you need add this condition
else if(left.Type==typeof(Guid) && right.Type==typeof(string)){
    right = Expression.Call(typeof(Guid).GetMethod("Parse"), right);
}
//end condition
else {
    CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures), op.text, ref left, ref right, op.pos);
}
....

then your query will execute

var result = source.Entities.Where("CompanyId = @0", new object[] { "838AD581-CEAB-4B44-850F-D05AB3D791AB" });
1
2/8/2014 1:23:34 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow