Answer the question
In order to leave comments, you need to log in
How to dynamically change the selection criterion in the Entity framework?
Good day, Toasterians!
I decided to get acquainted with the Entity Framework. For the universality of the script, you need to make a selection in the same table according to one of the three criteria. In the future, with all the results will be the same processing.
Current implementation:
var targetType = "G"; //целевой тип отчета. G - группа, T - преподаватель, C - кабинет
int targetId = 2; // ID целевой группы/препода/кабинета
var loadDb = db.Events.Where(l => l.cabinet == targetId.ToString());
switch (targetType)
{
case "G": loadDb = db.Events.Where(l => l.group == targetId.ToString()); break;
case "T": loadDb = db.Events.Where(l => l.teacher == targetId.ToString()); break;
case "C": loadDb = db.Events.Where(l => l.cabinet == targetId.ToString()); break;
default: targetType = "Error"; break;
}
switch (targetType)
{
case "G": запрос = l => l.group == targetId.ToString(); break;
case "T": запрос = l => l.teacher == targetId.ToString(); break;
case "C": запрос = l => l.cabinet == targetId.ToString(); break;
default: targetType = "Error"; break;
}
if (targetType != "Error")
{
var loadDb = db.Events.Where( запрос );
}
Answer the question
In order to leave comments, you need to log in
You are a little confused)
When you execute a line
You don't have a database query. In this line, only the query itself is created, that is, the sql code is generated based on your query. It doesn't go anywhere in the base. And is assigned to the loadDb variable
Next, when you do, for example,
You write another generated request to the loadDb variable. You are simply overwriting the variable. In this case, requests to the database are also not received.
Answering your question, most likely you want to impose an additional condition on one request. In your code it will look something like this:
var loadDb = db.Events.Where(l => l.cabinet == targetId.ToString());
switch (targetType)
{
case "G": loadDb = loadDb.Where(l => l.group == targetId.ToString()); break;
...
var res = loadDb.ToList()
What is the problem? Where performs a predicate, i.e. you need something like
Func<тип записи, bool> запрос;
switch (targetType)
{
case "G": запрос = l => l.group == targetId.ToString(); break;
case "T": запрос = l => l.teacher == targetId.ToString(); break;
case "C": запрос = l => l.cabinet == targetId.ToString(); break;
default: targetType = "Error"; break;
}
if (targetType != "Error")
{
var loadDb = db.Events.Where( запрос );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question