Error in expression [duplicate] - c#

This question already has answers here:
Linq Convert.ToInt32 in Query
(2 answers)
Closed 4 years ago.
Can anyone help me with the following error?
LINQ to Entities does not recognize the method 'Int32
Int32(System.String)' method, and this method cannot be translated
into a store expression.
Below is my code, I am trying in several ways to fix this error, but I have not been successful:
public IEnumerable<Dia1> GetPendenciasByUser(int centroId)
{
var query = Db.Dia1S
.Join(Db.Cadastros, dia1 => dia1.PatientId, cad => cad.PatientId, (dia1, cad) => new { dia1, cad })
.Join(Db.Randomizacao, dia1 => dia1.dia1.PatientId, rand => rand.PatientId, (dia1, rand) => new { dia1, rand })
.Where(s => s.dia1.dia1.dtd1 == null ? (Convert.ToInt32(DateTime.Now - s.rand.RandomizacaoData)) > 1 : (Convert.ToInt32(Convert.ToDateTime(s.dia1.dia1.dtd1) - s.rand.RandomizacaoData)) > 1 )
.Select(s => s.dia1.dia1)
.ToList();
return query;
}

The error message is clear, LINQ doesn't know how to convert the Convert.ToInt32() function to SQL. You can either use direct casting like this:
(int)(DateTime.Now - s.rand.RandomizacaoData)
Or you'll have to execute the query and get the data, then convert it in memory using Convert.ToInt32() as you wish.

Related

How many times will Linq to Objects iterate over a source? [duplicate]

This question already has answers here:
What are the benefits of a Deferred Execution in LINQ?
(3 answers)
What do they mean when they say LINQ is composable?
(2 answers)
Numbers of iteration generated in a single LINQ query
(1 answer)
Closed 3 years ago.
Say I have a simple Linq query:
var x = words.Where(w => w.Length > 4).Select(w => w.ToUpper()).ToArray();
Will the compiler generate code that iterates over words once, filtering and transforming as it goes, or code that generates an intermediate enumeration and then iterates over that?
What if there's an OrderBy():
var x = words.Where(w => w.Length > 4).OrderBy(w => w).Select(w => w.ToUpper()).ToArray();
I could see the compiler either iterating once over words, filtering and uppercasing words as it goes and merging them into an already sorted IOrderedEnumerable, or I could see it generating an intermediate array, sorting that, and then transforming it.
Rewrite the query as follows to see the flow of the data.
var x = words
.Where(w =>
{
Console.WriteLine("Where: " + w);
return w.Length > 4;
})
.Select(w =>
{
Console.WriteLine("Select: " + w);
return w.ToUpper();
})
.ToArray();

Multiple OrderBy not ordering correctly [duplicate]

This question already has answers here:
Multiple "order by" in LINQ
(7 answers)
Closed 3 years ago.
I'm trying to order by WeekId, then Order in my SQL table (end result should have workouts together by id, then ordered by the order specified), yet it is giving the wrong order. Is there something wrong with my LINQ statement?
private List<Workout> GetWorkouts(int id)
{
return new OPPDBContext().Workouts
.Where(p=>p.ClientId == id).OrderBy(p => p.Order).OrderBy(p => p.WeekId).ToList();
}
The table:
The results:
Expected results:
Lat Pulldowns
Squats
Lat Pulldowns
Squats
Reverse Lunges
That's because the second .OrderBy replaces the first .OrderBy (you are sorting by ClientId, and then effectively discard that to sort by WeekId).
You need to use .OrderBy(...).ThenBy(...) instead:
return new OPPDBContext().Workouts.Where(p=>p.ClientId == id).OrderBy(p => p.Order).ThenBy(p => p.WeekId).ToList();
OrderBy docs
ThenBy docs

Tuples - Only parameterless constructors and initializers are supported in LINQ to Entities [duplicate]

This question already has answers here:
How can I extract a list of Tuple from a specific table with Entity Framework / LINQ?
(2 answers)
Closed 8 years ago.
I want to load a list of tuples from database. However, when tried like below. I am getting an error "Only parameterless constructors and initializers are supported in LINQ to Entities".
List<Tuple<string, DateTime?>> schdule = new List<Tuple<string, DateTime?>>();
schdule = Entities.ScheduleDates.Where(x => x.Code == cCode).Select(x => new Tuple<string, DateTime?>(x.Key, x.Time)).ToList<Tuple<string, DateTime?>>();
However, by using anonymous types I don't get any error.
var tempSchedule = Entities.ScheduleDates.Where(x => x.Code == cCode).Select(x => new { x.Key, x.Time }).ToList();
Why I am facing the above error.
Because LINQ to Entities queries are translated to SQL queries, so each operation you do must have an equivalent in SQL.
Constructors which are nothing more than methods can't be translated.
But instantiating an anonymous type can, it will simply be translated as:
SELECT someAlias.Key, someAlias.Time ...

Linq to Entities "does not recognize the method ... method, and this method cannot be translated into a store expression." [duplicate]

This question already has an answer here:
Method cannot be translated into a store expression
(1 answer)
Closed 9 years ago.
I have a problem. I create a Data Entity Model in Visual Studio. And in Linq;
Guid RtuDataId = db.RtuData.Where(x => x.CommunicationUnit.Id == new Guid(ID))
.OrderByDescending(x => x.ReadOn)
.LastOrDefault().Id;
I get error ;
does not recognize the method ... method, and this method cannot be translated into a store expression.
I searched in Google but I don't understand this error.
Its LastOrDefault which is not supported in LINQ to Entites. I am not sure why you are using OrderByDescending, instead you can use OrderBy and then select First. Also its better if you create new Guid before your query and then pass it to your where clause like:
var guid = new Guid(ID);
Guid RtuDataId = db.RtuData
.Where(x => x.CommunicationUnit.Id == guid)
.OrderBy(x => x.ReadOn)
.FirstOrDefault()
.Id;
Since FirstOrDefault may return null, so you should check for null before accessing Id

LINQ to Entities does not recognize the method and this method cannot be translated into a store expression [duplicate]

This question already has answers here:
LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)'
(3 answers)
Closed 6 years ago.
var ps = dbContext.SplLedgers.Select(p => new SplLedgerModel
{
Name = p.Name,
VoucherType = Convert.ToString(((JIMS.VoucherTypes)p.VoucherType))
});
I am getting the following exception, whats wrong with the code.
JIMS.VoucherType is an enum
+ $exception {"LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method, and this method cannot be translated into a store expression."} System.Exception {System.NotSupportedException}
Your code is basically trying to find the Convert.ToString() method in the DB and understandably failing.
You can get around it, for example by making sure the query executes before the select, e.g.
var ps = dbContext.SplLedgers.Select(p => new
{
Name = p.Name,
VoucherType = p.VoucherType
}).ToList().Select(p => new SplLedgerModel(
{
Name = p.Name,
VoucherType = Convert.ToString(((JIMS.VoucherTypes)p.VoucherType))
});

Categories