Unable to cast the type 'System.Int32' to type 'System.Object during EF Code First Orderby Function












6















I'm using Specification pattern in EF Code First. When I do order by operation, VS throw a new exception



enter image description here



The specification pattern is copy from eShopOnWeb



I just change a little bit, here is my change code:



public class Specification<T> : ISpecification<T>
{

public Expression<Func<T, object>> OrderBy { get; private set; }

public Specification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}

public Specification<T> OrderByFunc(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
return this;
}
}


Here is my invoke code, it's very pretty simple:



static void TestSpec()
{
var spec = new Specification<ExcelData>(x => x.RowIndex == 5)
.OrderByFunc(x => x.ColumnIndex);

using (var dbContext = new TechDbContext())
{
var top10Data = dbContext.ExcelData.Take(10).ToList();
var listExcel = dbContext.ApplySpecification(spec).ToList();

Console.WriteLine();
}
}


If I comment OrderByFunc, then everything is fine to me. no error throw from vs.



I had try many times search the error message in google, but none of answer is my case.



So I have to ask a question in here.



When I debug OrderBy property in SpecificationEvaluator.cs, I found there is a Convert method.
enter image description here



So I know the error is about cast error, but how do I fix this cast type error?



Please help me!










share|improve this question























  • What does ApplySpecification do?

    – DevilSuichiro
    Dec 31 '18 at 8:26











  • return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

    – jeffrey chan
    Dec 31 '18 at 8:43
















6















I'm using Specification pattern in EF Code First. When I do order by operation, VS throw a new exception



enter image description here



The specification pattern is copy from eShopOnWeb



I just change a little bit, here is my change code:



public class Specification<T> : ISpecification<T>
{

public Expression<Func<T, object>> OrderBy { get; private set; }

public Specification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}

public Specification<T> OrderByFunc(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
return this;
}
}


Here is my invoke code, it's very pretty simple:



static void TestSpec()
{
var spec = new Specification<ExcelData>(x => x.RowIndex == 5)
.OrderByFunc(x => x.ColumnIndex);

using (var dbContext = new TechDbContext())
{
var top10Data = dbContext.ExcelData.Take(10).ToList();
var listExcel = dbContext.ApplySpecification(spec).ToList();

Console.WriteLine();
}
}


If I comment OrderByFunc, then everything is fine to me. no error throw from vs.



I had try many times search the error message in google, but none of answer is my case.



So I have to ask a question in here.



When I debug OrderBy property in SpecificationEvaluator.cs, I found there is a Convert method.
enter image description here



So I know the error is about cast error, but how do I fix this cast type error?



Please help me!










share|improve this question























  • What does ApplySpecification do?

    – DevilSuichiro
    Dec 31 '18 at 8:26











  • return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

    – jeffrey chan
    Dec 31 '18 at 8:43














6












6








6


0






I'm using Specification pattern in EF Code First. When I do order by operation, VS throw a new exception



enter image description here



The specification pattern is copy from eShopOnWeb



I just change a little bit, here is my change code:



public class Specification<T> : ISpecification<T>
{

public Expression<Func<T, object>> OrderBy { get; private set; }

public Specification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}

public Specification<T> OrderByFunc(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
return this;
}
}


Here is my invoke code, it's very pretty simple:



static void TestSpec()
{
var spec = new Specification<ExcelData>(x => x.RowIndex == 5)
.OrderByFunc(x => x.ColumnIndex);

using (var dbContext = new TechDbContext())
{
var top10Data = dbContext.ExcelData.Take(10).ToList();
var listExcel = dbContext.ApplySpecification(spec).ToList();

Console.WriteLine();
}
}


If I comment OrderByFunc, then everything is fine to me. no error throw from vs.



I had try many times search the error message in google, but none of answer is my case.



So I have to ask a question in here.



When I debug OrderBy property in SpecificationEvaluator.cs, I found there is a Convert method.
enter image description here



So I know the error is about cast error, but how do I fix this cast type error?



Please help me!










share|improve this question














I'm using Specification pattern in EF Code First. When I do order by operation, VS throw a new exception



enter image description here



The specification pattern is copy from eShopOnWeb



I just change a little bit, here is my change code:



public class Specification<T> : ISpecification<T>
{

public Expression<Func<T, object>> OrderBy { get; private set; }

public Specification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}

public Specification<T> OrderByFunc(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
return this;
}
}


Here is my invoke code, it's very pretty simple:



static void TestSpec()
{
var spec = new Specification<ExcelData>(x => x.RowIndex == 5)
.OrderByFunc(x => x.ColumnIndex);

using (var dbContext = new TechDbContext())
{
var top10Data = dbContext.ExcelData.Take(10).ToList();
var listExcel = dbContext.ApplySpecification(spec).ToList();

Console.WriteLine();
}
}


If I comment OrderByFunc, then everything is fine to me. no error throw from vs.



I had try many times search the error message in google, but none of answer is my case.



So I have to ask a question in here.



When I debug OrderBy property in SpecificationEvaluator.cs, I found there is a Convert method.
enter image description here



So I know the error is about cast error, but how do I fix this cast type error?



Please help me!







entity-framework casting sql-order-by specifications






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 31 '18 at 8:04









jeffrey chanjeffrey chan

7011




7011













  • What does ApplySpecification do?

    – DevilSuichiro
    Dec 31 '18 at 8:26











  • return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

    – jeffrey chan
    Dec 31 '18 at 8:43



















  • What does ApplySpecification do?

    – DevilSuichiro
    Dec 31 '18 at 8:26











  • return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

    – jeffrey chan
    Dec 31 '18 at 8:43

















What does ApplySpecification do?

– DevilSuichiro
Dec 31 '18 at 8:26





What does ApplySpecification do?

– DevilSuichiro
Dec 31 '18 at 8:26













return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

– jeffrey chan
Dec 31 '18 at 8:43





return SpecificationEvaluator<T>.GetQuery(_dbContext.Set<T>().AsQueryable(), spec);

– jeffrey chan
Dec 31 '18 at 8:43












1 Answer
1






active

oldest

votes


















3





+50









The solution is to create new lambda expression with cast (Convert) removed, and then use it to call the Queryable class OrderBy / OrderByDescending method either dynamically (using DLR dispatch or reflection) or by emitting Expression.Call to it.



For the first part, add the following helper method to the SpecificationEvaluator class:



static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}


Then replace the code



query = query.OrderBy(specification.OrderBy);


with either



query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));


or



var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));


Do similar for the specification.OrderByDescending.






share|improve this answer



















  • 1





    Hi Ivan, you help me a lot on this. Thanks a lot.

    – jeffrey chan
    Jan 5 at 6:04











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985059%2funable-to-cast-the-type-system-int32-to-type-system-object-during-ef-code-fir%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3





+50









The solution is to create new lambda expression with cast (Convert) removed, and then use it to call the Queryable class OrderBy / OrderByDescending method either dynamically (using DLR dispatch or reflection) or by emitting Expression.Call to it.



For the first part, add the following helper method to the SpecificationEvaluator class:



static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}


Then replace the code



query = query.OrderBy(specification.OrderBy);


with either



query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));


or



var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));


Do similar for the specification.OrderByDescending.






share|improve this answer



















  • 1





    Hi Ivan, you help me a lot on this. Thanks a lot.

    – jeffrey chan
    Jan 5 at 6:04
















3





+50









The solution is to create new lambda expression with cast (Convert) removed, and then use it to call the Queryable class OrderBy / OrderByDescending method either dynamically (using DLR dispatch or reflection) or by emitting Expression.Call to it.



For the first part, add the following helper method to the SpecificationEvaluator class:



static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}


Then replace the code



query = query.OrderBy(specification.OrderBy);


with either



query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));


or



var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));


Do similar for the specification.OrderByDescending.






share|improve this answer



















  • 1





    Hi Ivan, you help me a lot on this. Thanks a lot.

    – jeffrey chan
    Jan 5 at 6:04














3





+50







3





+50



3




+50





The solution is to create new lambda expression with cast (Convert) removed, and then use it to call the Queryable class OrderBy / OrderByDescending method either dynamically (using DLR dispatch or reflection) or by emitting Expression.Call to it.



For the first part, add the following helper method to the SpecificationEvaluator class:



static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}


Then replace the code



query = query.OrderBy(specification.OrderBy);


with either



query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));


or



var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));


Do similar for the specification.OrderByDescending.






share|improve this answer













The solution is to create new lambda expression with cast (Convert) removed, and then use it to call the Queryable class OrderBy / OrderByDescending method either dynamically (using DLR dispatch or reflection) or by emitting Expression.Call to it.



For the first part, add the following helper method to the SpecificationEvaluator class:



static LambdaExpression RemoveConvert(LambdaExpression source)
{
var body = source.Body;
while (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return Expression.Lambda(body, source.Parameters);
}


Then replace the code



query = query.OrderBy(specification.OrderBy);


with either



query = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(specification.OrderBy));


or



var keySelector = RemoveConvert(specification.OrderBy);
query = query.Provider.CreateQuery<T>(Expression.Call(
typeof(Queryable), nameof(Queryable.OrderBy),
new { typeof(T), keySelector.ReturnType },
query.Expression, keySelector));


Do similar for the specification.OrderByDescending.







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 4 at 17:54









Ivan StoevIvan Stoev

103k774126




103k774126








  • 1





    Hi Ivan, you help me a lot on this. Thanks a lot.

    – jeffrey chan
    Jan 5 at 6:04














  • 1





    Hi Ivan, you help me a lot on this. Thanks a lot.

    – jeffrey chan
    Jan 5 at 6:04








1




1





Hi Ivan, you help me a lot on this. Thanks a lot.

– jeffrey chan
Jan 5 at 6:04





Hi Ivan, you help me a lot on this. Thanks a lot.

– jeffrey chan
Jan 5 at 6:04


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985059%2funable-to-cast-the-type-system-int32-to-type-system-object-during-ef-code-fir%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Mossoró

Error while reading .h5 file using the rhdf5 package in R

Pushsharp Apns notification error: 'InvalidToken'