Dynamic LINQ: Comparing Nested Data with Parent Property
I have a class with the following structure:
public class BestWayContext
{
public Preference Preference { get; set; }
public DateTime DueDate { get; set; }
public List<ServiceRate> ServiceRate { get; set; }
}
public class ServiceRate
{
public int Id { get; set; }
public string Carrier { get; set; }
public string Service { get; set; }
public decimal Rate { get; set; }
public DateTime DeliveryDate { get; set; }
}
and I have a dynamic linq expression line
"Preference! = Null && ServiceRate.Any (Carrier == Preference.Carrier)"
and I want to convert the above string to Dynamic LINQ like this:
var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, null).Compile();
But it shows the following error:
Please correct me, what am I doing wrong?
+3
source to share
2 answers
It looks like you wanted to do something like this:
var bwc = new BestWayContext
{
Preference = new Preference { Carrier = "test" },
DueDate = DateTime.Now,
ServiceRate = new List<ServiceRate>
{
new ServiceRate
{
Carrier = "test",
DeliveryDate = DateTime.Now,
Id = 2,
Rate = 100,
Service = "testService"
}
}
};
string condition = "Preference != null && ServiceRate.Any(Carrier == @0)";
var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, bwc.Preference.Carrier).Compile();
bool res = expression(bwc); // true
bwc.ServiceRate.First().Carrier = "test1"; // just for testing this -> there is only one so I've used first
res = expression(bwc); // false
0
source to share
You want to use the Preference that is owned by BestWayContext, but you haven't told the compiler about it. If I write your expression in Linq I do the following:
[BestWayContext List]. Where (f => f.Preference! = Null && f.ServiceRate.Where (g => g.Carrier == f.Preference.Carrier));
As you can see I have indicated to use the Preference BestWayContext.
0
source to share