1

I am trying to build a dynamic query using Linq.Dynamic.Core. So the idea is that the query needs to execute based on various conditions like Contains,AND,OR. All of those are working fine but greater than and less than a date value is failing.

I have tried a couple of versions but both don't seem to work. Following is the main query.

var result = context.AllResults.Where(where).Distinct().AsEnumerable();

So the 'where' is what I am trying to build as a generic query. The below was working before but now it throws and error "Operator '<' incompatible with operand types 'DateTime' and 'Int32'"

var dtValue = (DateTime)value;
where = String.Format("{0} <= DateTime({1},{2},{3},{4},{5},{6})", field, dtValue.Year, dtValue.Month, dtValue.Day, dtValue.Hour, dtValue.Minute, dtValue.Second);

I have tried an alternative but that does not seem to work and throws the same issue.

var dtValue = (DateTime)value;
where = String.Format("{0} <= {1}",field, DateTime.Parse(dtValue.ToShortDateString()));

I have looked at the various solutions but none seem to work. What am I doing wrong? Also this is a simplified version of a bigger query, so using the value directly instead of where in the main query does not work.

TheFallenOne
  • 1,598
  • 2
  • 23
  • 57
  • Why can’t you simply compare the dates? Something like date1 <= date2? – Vivek Nuna Oct 12 '21 at 17:20
  • @viveknuna Because the condition can be dynamic. It's not always a date comparison, it can be a contains operation, an AND operation. So I need it to be dynamic to ensure it handles all cases. I have presented only the issue which I am facing in the example to reduce complexity. – TheFallenOne Oct 12 '21 at 17:22

1 Answers1

2

I was facing a similar issue and this is how I went about fixing it. The solution I got from Linq.Dynamic.Core github site.

So basically you have to add the Entity class(table column) with the Column attribute and specifying the TypeName:

[Column(TypeName = "datetime")]
public DateTime MyDateTimeField { get; set; }

This needs to be applied to the date column you are trying to compare the value with.

The_Outsider
  • 1,875
  • 2
  • 24
  • 42