I have one LINQ Query with custom model. I just wanted to use a method to assign a value for a model property. But When I try to use the custom model it throws some error message like this:
LINQ to Entities does not recognize the method 'System.String GetPONo(Ent, System.String)' method, and this method cannot be translated into a store expression.
Code
var model = (from p in db.PoDetails
select new porders
{
Category = p.Category,
PONO = GetPONo(p, p.Category),
}).ToList();
Method
public string GetPONo(PoDetail p, string ASD)
{
if (ASD == "B")
{
var PoNo = (from pord in db.Porders where pord.Id == p.PoId select pord.No).FirstOrDefault();
return PoNo;
}
else
{
var PoNo = (from porder in db.Porders
where porder.Id == (from rec in db.RecommendResources where rec.Id == p.BibId select rec.PoId).FirstOrDefault()
select porder.No).FirstOrDefault();
return PoNo;
}
}
var q = (from a in v.A join b in v.B on a.i equals b.j where a.k == "aaa" && a.h == 0 select new {T = a.i, S = someMethod(a.z). ToString()}) return q; The line S = someMethod(a.z).
This is because LINQ to Entities is translated to SQL behind the scenes. Of course there isn't a GetPONo(p, p.Category)
method in SQL so your code will fail. You can solve this by calling ToList()
to force the query to run before your select
.
var model = (from p in db.PoDetails select p).ToList();
model = from m in model
select new porders
{
Category = m.Category,
PONO = GetPONo(m, m.Category)
};
You can take a look at my answer to a similar question here
You can use ternary operator to do different subquery for PONO depending on category value
var model = (from p in db.PoDetails
select new porders
{
Category = p.Category,
PONO = p.Category == "B" ?
(from pord in db.Porders
where pord.Id == p.PoId
select pord.No).FirstOrDefault() :
(from porder in db.Porders
where porder.Id == (from rec in db.RecommendResources
where rec.Id == p.BibId
select rec.PoId).FirstOrDefault()
select porder.No).FirstOrDefault()
}).ToList();
Also you can create stored procedure for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With