Entity Framework - ridiculous Query, casting smallint to int for comparison [duplicate]

梦想的初衷 提交于 2019-12-01 03:36:20
Ilya

This behavior can be common for different LINQ providers and not only EF-specific, because of how C# compiler generates expression tree for your Where expression.

When you specify condition as:

.Where(x => x.BucketRef == bucketId)

and both BucketRef and bucketId are shorts, compiler generates cast from short to int for both parts of comparison, because == operator isn't defined for Short type. This is explained in answer https://stackoverflow.com/a/18584429/869184

As a workaround you can rewrite condition the following way:

.Where(x => x.BucketRef.Equals(bucketId))

This effectively removes cast from comparison.

You need to create the Where expression yourself using the static functions in the Expression class.

Like this:

Int16 bucketId = 3;

var parameter = Expression.Parameter(typeof(SimStgTrade));
var property = Expression.PropertyOrField(parameter, "BucketRef");
var constant = Expression.Constant(bucketId);
var comparison = Expression.Equal(property, constant);

var lambda = Expression.Lambda<Func<SimStgTrade,bool>>(comparison, parameter);

var tradesQuery = repository.SimStgTrade
  .Where(lambda)
  .Where(x => x.VariantNo == set)
  .ToArray();

Do the same for VariantNo == set in order to remove that cast as well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!