How to build Linq query dynamically based on certain conditions - c#

I have a data entry form where user will input DateFrom and DateTo fields.
Select From Date: <input type="text" id="datepickerfrom" name="datepickerfrom"/>
Select To Date: <input type="text" id="datepickerto" name="datepickerto"/>
<asp:Button ID="btnGetData" runat="server" OnClick="BtnGetData_Click" Text="Get Error List" />
I want to build a Linq query that retrieves only top 100 records in case if no input provided.
If user provides DateFrom and does not provide DateTo, the user will select data which is greater than DateFrom up to DateTime.Now.
If user provides DateTo and does not provide DateFrom, the user will select data which is less then DateTo.
I have the following now:
public static List<ErrorLogData> GetLogErrorData(string appName, InputData data)
{
SqlConnection con;
List<ErrorLogData> errorLogData = null;
string query = "";
if (data.DateFrom == "" && data.DateTo == "")
{
query += "from ld in logData.errorLogs.Take(10000)";
}
if (data.DateFrom == "" && data.DateTo != "")
{
query += "from ld in logData.errorLogs where ld.errorTime <= " + data.DateTo;
}
if (data.DateFrom != "" && data.DateTo == "")
{
query += "from ld in logData.errorLogs where ld.errorTime >= " + data.DateFrom + " && <= " + DateTime.Now;
}
if (data.DateFrom != "" && data.DateTo != "")
{
query += "from ld in logData.errorLogs where ld.errorTime >= " + data.DateFrom + " && <= " + data.DateTo;
}
DateTime dateFrom = Convert.ToDateTime(data.DateFrom);
DateTime dateTo = Convert.ToDateTime(data.DateTo);
using (con = new SqlConnection(ConfigurationManager.AppSettings[conKey]))
using (WebEntities logData = new WebEntities())
{
logData.CommandTimeout = 300;
var errorLog = query +
select new ErrorLogData
{
ErrorID = ld.errorID,
ErrorTime = ld.errorTime,
UserName = ld.username,
ErrorType = ld.errorType,
Error = ld.error,
ControlNumber = ld.controlNumber
};
errorLogData = errorLog.ToList();
}
return errorLogData;
}
I'm not sure how to append query to "select new ErrorLogData..." statement to have the entire query.
What is the approach here?

You should just be able to use the IQueryable result of error log, and then perform lambda expressions for your if statements.
List<ErrorLogData> errorLogData = null;
DateTime dateFrom = Convert.ToDateTime(data.DateFrom);
DateTime dateTo = Convert.ToDateTime(data.DateTo);
//IQueryable errorLog
var errorLog = from ld in logData.errorLogs
select new ErrorLogData
{
ErrorID = ld.errorID,
ErrorTime = ld.errorTime,
UserName = ld.username,
ErrorType = ld.errorType,
Error = ld.error,
ControlNumber = ld.controlNumber
};
if (data.DateFrom == "" && data.DateTo == "")
{
errorLogData = errorLog.Take(10000);
}
if (data.DateFrom == "" && data.DateTo != "")
{
errorLogData = errorLog.where(x => x.ErrorTime <= dateTo).ToList();
//query += "from ld in logData.errorLogs where ld.errorTime <= " + data.DateTo;
}
//contine to implement If
return errorLogData;

Assuming that you are using some kind of LINQ data access technology, use something like the following:
private List<Entity> GetData(DateTime? dateFrom, DateTime? dateTo)
{
IQueryable<Entity> query = ...; //Here reference your table
if (dateFrom == null && dateTo == null)
{
query = query.Take(100);
}
else
{
DateTime dateToValue = dateTo ?? DateTime.Now;
query = query.Where(x => x.Date <= dateToValue);
if (dateFrom != null)
{
query = query.Where(x => x.Date >= dateFrom.Value);
}
}
return query.ToList(); //This will actually execute the query. Here you can expand your query to select specific columns before executing ToList
}

Related

Trying to retrieve data from multiple related tables in mysql from very big data

I know this question has been asked several time, but I been trying to get data from many to many related multiple tables in mysql table. Also, each table contains minimum of 500000 records. How can speed up the data retrieving process in this case ?
Although, I have try to get data using group by to prepare data according to screen but it still working very slow.
In controller of screen I have used group by using linq.
var lstclientId = (from c in DBContext.groupmasters.Where(w => w.isactive == true && w.UserID == userid)
group c by c.ClientID into d
select new
{
clientID = d.Key,
});
var lstJobTypeID = (from c in DBContext.jobrequisitions.Where(w => w.ISActive == true)
group c by new { c.CreativeID, c.ProjectName, c.client.ClientName, c.brandmaster.branddesc } into d
select new
{
CreativeID = d.Key.CreativeID,
ProjectName = d.Key.ProjectName,
ClientName = d.Key.ClientName,
branddesc = d.Key.branddesc,
}).OrderBy(o => o.CreativeID);
List<jobrequisition> lstrequisition = new List<jobrequisition>();
List<jobrequisition> lstrequisitionusers = new List<jobrequisition>();
if ((Session["deptCode"]).ToString() == "QC" || (Session["deptCode"]).ToString() == "OP" || Convert.ToBoolean(Session["IsAdmin"]) == true)
{
database2Entities JobEntities = new database2Entities();
lstrequisition = JobEntities.jobrequisitions.Where(w => w.ISActive == true).ToList();
lstrequisitionusers.AddRange(lstrequisition);
}
else
{
foreach (var i in lstclientId)
{
database2Entities JobEntities = new database2Entities();
lstrequisition = JobEntities.jobrequisitions.Where(w => w.ISActive == true && w.ClientID == i.clientID).ToList();
lstrequisitionusers.AddRange(lstrequisition);
}
}
Hashtable ht = new Hashtable();
int k = 0;
foreach (var i in lstJobTypeID)
{
foreach (jobrequisition objRequestion in lstrequisitionusers.OrderBy(o => o.CreativeID))
{
if (objRequestion.CreativeID == i.CreativeID)
{
database2Entities ArtContext = new database2Entities();
database2Entities SubArtContext = new database2Entities();
if (lstArtWorkReqID.Count() == 0)
{
///old code...
var lstArt = ArtContext.artworkrequisitions.SqlQuery("SELECT *, count(ArtWorkName) as awtname FROM artworkrequisition as awt group by ArtWorkID having CreativeID = '" + i.CreativeID + "' and IsActive = 1").ToList();
foreach (artworkrequisition art in lstArt)
{
int isCompletedcount = 0, assigncount = 0, allitemcount = 0, jobassignedcount = 0, iscompletedjobcount = 0;
List<artworkrequisition> allartworkitems = SubArtContext.artworkrequisitions.Where(w => w.ArtWorkID == art.ArtWorkID && w.IsActive == true).ToList();
jobassignedcount = allartworkitems.Where(w => w.isAssigned == true).Count();
allitemcount = allartworkitems.Where(w => w.IsActive == true).Count();
if (jobassignedcount > 0)
{
if (jobassignedcount <= allitemcount)
{
foreach (artworkrequisition singleartitem in allartworkitems)
{
if (singleartitem.isAssigned == null && singleartitem.isAssigned == true)
{
job_assigned_employee allocatedjobdetails = SubArtContext.job_assigned_employee.Where(w => w.ItemJobReqID == singleartitem.Id && w.JobTypeID == 1 && w.JobReqNo == singleartitem.ArtWorkID && w.IsActive == true).FirstOrDefault();
if (allocatedjobdetails.IsCompelete == true)
{
iscompletedjobcount += 1;
}
}
}
if (iscompletedjobcount < allitemcount)
{
lstArtWorkReqID.Add(art);
}
}
}
else
{
lstArtWorkReqID.Add(art);
}
}
}
else
{
var lstArt = ArtContext.artworkrequisitions.SqlQuery("SELECT *, count(ArtWorkName) awtname FROM artworkrequisition awt group by ArtWorkID having CreativeID = '" + i.CreativeID + "' and IsActive = 1").ToList();
foreach (artworkrequisition art in lstArt)
{
int isCompletedcount = 0, assigncount = 0, allitemcount = 0, jobassignedcount = 0, iscompletedjobcount = 0;
List<artworkrequisition> allartworkitems = SubArtContext.artworkrequisitions.Where(w => w.ArtWorkID == art.ArtWorkID && w.IsActive == true).ToList();
jobassignedcount = allartworkitems.Where(w => w.isAssigned == true).Count();
allitemcount = allartworkitems.Where(w => w.IsActive == true).Count();
if (jobassignedcount > 0)
{
if (jobassignedcount <= allitemcount)
{
foreach (artworkrequisition singleartitem in allartworkitems)
{
if (singleartitem.isAssigned != null && singleartitem.isAssigned == true)
{
job_assigned_employee allocatedjobdetails = SubArtContext.job_assigned_employee.Where(w => w.ItemJobReqID == singleartitem.Id && w.JobTypeID == 1 && w.JobReqNo == singleartitem.ArtWorkID && w.IsActive == true).FirstOrDefault();
if (allocatedjobdetails != null)
{
if (allocatedjobdetails.IsCompelete != null && allocatedjobdetails.IsCompelete == true)
{
iscompletedjobcount += 1;
}
}
}
}
if (iscompletedjobcount <= jobassignedcount && iscompletedjobcount != allitemcount)
{
lstArtWorkReqID.Add(art);
}
}
}
else
{
lstArtWorkReqID.Add(art);
}
// job_assigned_employee allocatedjobdetails = SubArtContext.job_assigned_employee.Where(w => w.ItemJobReqID == singleartitem.Id && w.JobTypeID == 1 && w.JobReqNo == singleartitem.ArtWorkID && w.IsActive == true).FirstOrDefault();
}
}
if (lstPhotoStockReq.Count() == 0)
{
var lstPhotoStock = ArtContext.photographyrequisitions.SqlQuery("SELECT * FROM photographyrequisition where CreativeNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by photographyReqNo").ToList();
foreach (photographyrequisition objphot in lstPhotoStock)
{
lstPhotoStockReq.Add(objphot);
}
}
else
{
var lstPhotoStock = ArtContext.photographyrequisitions.SqlQuery("SELECT * FROM photographyrequisition where CreativeNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by photographyReqNo").ToList();
foreach (photographyrequisition objphot in lstPhotoStock)
{
lstPhotoStockReq.Add(objphot);
}
}
if (lstInterActiveWorkReq.Count() == 0)
{
var lstinteractivereq = ArtContext.interactiverequisitions.SqlQuery("SELECT * FROM interactiverequisition where CreativeID = '" + i.CreativeID + "' and isActive = 1 group by InteractiveID").ToList();
foreach (interactiverequisition objInter in lstinteractivereq)
{
lstInterActiveWorkReq.Add(objInter);
}
}
else
{
var lstinteractivereq = ArtContext.interactiverequisitions.SqlQuery("SELECT * FROM interactiverequisition where CreativeID = '" + i.CreativeID + "' and isActive = 1 group by InteractiveID").ToList();
foreach (interactiverequisition objInter in lstinteractivereq)
{
lstInterActiveWorkReq.Add(objInter);
}
}
if (lstTransWorkReq.Count() == 0)
{
var lstTranslatereq = ArtContext.translationrequisitions.SqlQuery("SELECT * FROM translationrequisition where creativeID = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by TransReqNo").ToList();
foreach (translationrequisition objTrans in lstTranslatereq)
{
lstTransWorkReq.Add(objTrans);
}
}
else
{
var lstTranslatereq = ArtContext.translationrequisitions.SqlQuery("SELECT * FROM translationrequisition where creativeID = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by TransReqNo").ToList();
foreach (translationrequisition objTrans in lstTranslatereq)
{
lstTransWorkReq.Add(objTrans);
}
}
if (lstPrintProductionReq.Count() == 0)
{
var lstPrintProductReq = ArtContext.printproductionrequisitions.SqlQuery("SELECT * FROM printproductionrequisition where CampaingNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by PrintProductionReqID").ToList();
foreach (printproductionrequisition objPrint in lstPrintProductReq)
{
lstPrintProductionReq.Add(objPrint);
}
}
else
{
var lstPrintProductReq = ArtContext.printproductionrequisitions.SqlQuery("SELECT * FROM printproductionrequisition where CampaingNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by PrintProductionReqID").ToList();
foreach (printproductionrequisition objPrint in lstPrintProductReq)
{
lstPrintProductionReq.Add(objPrint);
}
}
if (lstFilmProductionReq.Count() == 0)
{
var lstFilmproductionReq = ArtContext.filmproductionrequisitions.SqlQuery("SELECT * FROM filmproductionrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by FilmProductionReqID").ToList();
foreach (filmproductionrequisition objFilm in lstFilmproductionReq)
{
lstFilmProductionReq.Add(objFilm);
}
}
else
{
var lstFilmproductionReq = ArtContext.filmproductionrequisitions.SqlQuery("SELECT * FROM filmproductionrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by FilmProductionReqID").ToList();
foreach (filmproductionrequisition objFilm in lstFilmproductionReq)
{
lstFilmProductionReq.Add(objFilm);
}
}
if (lstRetainerFeeReq.Count() == 0)
{
var lstRetainerfeereq = ArtContext.retainerfeerequisitions.SqlQuery("SELECT * FROM retainerfeerequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by RetainerfeeReqID").ToList();
foreach (retainerfeerequisition objRetainer in lstRetainerfeereq)
{
lstRetainerFeeReq.Add(objRetainer);
}
}
else
{
var lstRetainerfeereq = ArtContext.retainerfeerequisitions.SqlQuery("SELECT * FROM retainerfeerequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by RetainerfeeReqID").ToList();
foreach (retainerfeerequisition objRetainer in lstRetainerfeereq)
{
lstRetainerFeeReq.Add(objRetainer);
}
}
if (lstStockImageReq.Count() == 0)
{
var lstStockImagereq = ArtContext.stockimagerequisitions.SqlQuery("SELECT * FROM stockimagerequisition where CampaginNo = '" + i.CreativeID + "' and IsActive = 1 and isApproved = 0 and statusId = 4 group by StockImageReqNo").ToList();
foreach (stockimagerequisition objStockImage in lstStockImagereq)
{
lstStockImageReq.Add(objStockImage);
}
}
else
{
var lstStockImagereq = ArtContext.stockimagerequisitions.SqlQuery("SELECT * FROM stockimagerequisition where CampaginNo = '" + i.CreativeID + "' and IsActive = 1 and isApproved = 0 and statusId = 4 group by StockImageReqNo").ToList();
foreach (stockimagerequisition objStockImage in lstStockImagereq)
{
lstStockImageReq.Add(objStockImage);
}
}
if (lstSystemWorkReq.Count() == 0)
{
var lstSystemWork = ArtContext.systemworkrequisitions.SqlQuery("SELECT * FROM systemworkrequisition where CampaignNo = '" + i.CreativeID + "' and IsActive = 1 and StatusID = 4 group by SystemReqNo").ToList();
foreach (systemworkrequisition systemwork in lstSystemWork)
{
lstSystemWorkReq.Add(systemwork);
}
}
else
{
var lstSystemWork = ArtContext.systemworkrequisitions.SqlQuery("SELECT * FROM systemworkrequisition where CampaignNo = '" + i.CreativeID + "' and IsActive = 1 and StatusID = 4 group by SystemReqNo").ToList();
foreach (systemworkrequisition systemwork in lstSystemWork)
{
lstSystemWorkReq.Add(systemwork);
}
}
if (lstOthersReq.Count() == 0)
{
var lstOthersreq = ArtContext.othersrequisitions.SqlQuery("SELECT * FROM othersrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by OtherReqNo").ToList();
foreach (othersrequisition objOthers in lstOthersreq)
{
lstOthersReq.Add(objOthers);
}
}
else
{
var lstOthersreq = ArtContext.othersrequisitions.SqlQuery("SELECT * FROM othersrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by OtherReqNo").ToList();
foreach (othersrequisition objOthers in lstOthersreq)
{
lstOthersReq.Add(objOthers);
}
}
if (lstTenderReq.Count() == 0)
{
var lstTendersreq = ArtContext.tender_noticerequisition.SqlQuery("SELECT *, count(TenderNoticeName) as tendername FROM tender_noticerequisition as awt group by tendernoticeID having CampaignNo = '" + i.CreativeID + "' and IsActive = 1").ToList();
foreach (tender_noticerequisition objTenders in lstTendersreq)
{
lstTenderReq.Add(objTenders);
}
}
else
{
var lstTendersreq = ArtContext.tender_noticerequisition.SqlQuery("SELECT *, count(TenderNoticeName) as tendername FROM tender_noticerequisition as awt group by tendernoticeID having CampaignNo = '" + i.CreativeID + "' and IsActive = 1").ToList();
foreach (tender_noticerequisition objTenders in lstTendersreq)
{
lstTenderReq.Add(objTenders);
}
}
if (lstillustrationreq.Count() == 0)
{
var lstillustrareq = ArtContext.illustrationrequisitions.SqlQuery("SELECT *,count(descriptions) FROM illustrationrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by IllustrationNo").ToList();
foreach (illustrationrequisition objillustra in lstillustrareq)
{
lstillustrationreq.Add(objillustra);
}
}
else
{
var lstillustrareq = ArtContext.illustrationrequisitions.SqlQuery("SELECT * FROM illustrationrequisition where CampaignNo = '" + i.CreativeID + "' and isActive = 1 and isApproved = 0 group by IllustrationNo").ToList();
foreach (illustrationrequisition objillustra in lstillustrareq)
{
lstillustrationreq.Add(objillustra);
}
}
string strprojectClient = i.ProjectName + "-" + i.ClientName + "-" + i.branddesc;
ht.Add(i.CreativeID, strprojectClient);
k++;
break;
}
}
}
I am able to get data like this
campaign no :100001 -> job no: 1001 entry date: 28-03-2019
I think that if you change:
from c in DBContext.jobrequisitions.Where(w => w.ISActive == true)
to something like
from c in DBContext.jobrequisitions
where c.ISActive == true
You might improve the performance a little bit, because, as far as I remember, the fluent version Where will execute as a separate query to the database, instead as part of the group by query, thus causing the database to generate a less efficient execution plan.
By the way, as a side note, I'd recommend not mixing between the SQL and fluent LINQ query syntaxes unless absolutely necessary.
Hope it helps!

LINQ query with value from dropdown to compare with data

My query is below. Can someone help me how to add dbquery inside my Linq statement? There is a comment "Add Where here". I'm struggling since yesterday. Idea is to form a LINQ statement and get the list at once. Thank you.
String dbwhere = "";
if (ddlName.SelectedItem.Value != "")
{
dbwhere = " && (User.Name == '" + ddlName.SelectedItem.Value.TrimEnd() + "')";
}
if (ddlHeightFrom.SelectedItem.Value != "")
{
dbwhere = dbwhere + " && (Physical.Height >= '" + ddlHeightFrom.SelectedItem.Value.TrimEnd() + "')";
}
if (ddlHeightTo.SelectedItem.Value != "")
{
dbwhere = dbwhere + " && (Physical.Height <= '" + ddlHeightTo.SelectedItem.Value.TrimEnd() + ")";
}
var usersquery = (
from physical in dbContext.Physicals
join user in dbContext.User on physical.UserID equals user.UserID
join photos in dbContext.Photo on User.UserID equals photos.UserID
where photos.PhotoNum == 1 && photos.Status == true
// ======= Add dbwhere here ============
select new
{
photos.PhotoURL,
photos.PhotoDescription,
user.State,
user.Country,
physical.EyesColor,
physical.HairColorInfo,
physical.HairTypeInfo,
physical.BodyHeight,
physical.BodyWeight,
}).ToList();
You can rewrite your query to avoid mixing linq with SQL (and make it safe from SQL injections)
var usersquery = (
from physical in dbContext.Physicals
join user in dbContext.User on physical.UserID equals user.UserID
join photos in dbContext.Photo on User.UserID equals photos.UserID
where photos.PhotoNum == 1 && photos.Status == true
select new
{
physical,
user,
photos,
}; // do not put ToList here!
Now you can add your special checks:
if (ddlName.SelectedItem.Value != "")
{
var userName = ddlName.SelectedItem.Value.TrimEnd();
usersquery = usersquery.Where(x => x.user.Name == userName);
}
if (ddlHeightFrom.SelectedItem.Value != "")
{
var height = int.Parse(ddlHeightFrom.SelectedItem.Value.TrimEnd());
usersquery = usersquery.Where(x => x.physical.Height >= height);
}
// and so on
Now you can materialize your data with ToList
var result = usersquery.Select(x => new
{
x.photos.PhotoURL,
x.photos.PhotoDescription,
x.user.State,
x.user.Country,
x.physical.EyesColor,
x.physical.HairColorInfo,
x.physical.HairTypeInfo,
x.physical.BodyHeight,
x.physical.BodyWeight
}).ToList();
NOTE: I've write it in notepad, so it may have errors. However I hope idea is clear

Dynamic Where Linq C#

I'm using System.Linq.Dynamic to make dinanmico where in my research. In the code below I try to filter by Funcao, but returns the error:
No property or field 'Funcao' exists in type 'ASO'
How do I filter by an alias of my Linq?
CODE
public static ResultadoListagemPadrao Grid(int iniciarNoRegistro, int qtdeRegistro, string orderna, string ordenaTipo, string filtro, int filtroID, UsuarioLogado usuarioLogado)
{
var where = "";
var id = 0;
if (filtroID > 0)
where += " FuncionarioID == " + filtroID.ToString();
else
{
if (int.TryParse(filtro, out id))
where += " ASOID == " + id.ToString();
if (filtro != null)
where += " Funcao.Contains(#0) ";
}
using (var db = new ERPContext())
{
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
resultado.TotalRegistrosVisualizados = db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro).Count();
resultado.Dados =
(from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro)
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
}
}
Issue is this line db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro)
Your class ASO doesn't have a property Funcao.
Try remove the Where on that line. Try this...
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
var query = (from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro);
resultado.TotalRegistrosVisualizados = query.Count();
resultado.Dados = query
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
Please in future translate your code.

Multimode Search in Entity Framework

The code is listed below , is my code for multimode search in ado.net , i use now entity framework and i dont know how write this perfectly with less code
string query = '"SELECT id From user";
if(filter1 != "" || filter2 != "")
{
query += "where ";
}
if(filter1 != "")
{
query += "name='" + filter1 + "'";
if(filter2 != "")
query += " and "
}
if(filter2 != "")
query += "name" + filter2;
Try this:
var result = (from s in db.user
select s).AsQueryable();
if (filter1 != "")
{
result = result.Where(x=>x.name == filter1);
}
if (filter2 != "")
{
result = result.Where(x=>x.name == filter2);
}
var output = result.ToList();
Sample:
YourIQueryableResults.Where(x => filter1!="" && (x.Name == filter1))
or
if (filter1!="") { YourIQueryableResults = YourIQueryableResults.Where(x => x.Name == filter1)}

Multiple Binding Source Filters

I have a simple database and I'm trying to make it searchable with multiple criteria. What I do not know is how to get the datagridview to filter using these various criteria all together. I'm doing it very messily I know with the if else statements. If I filter with the combobox, it will disregard all my other criteria. Here's my basic code:
if (StartDate < EndDate)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Suggestion Date] >= #{0:M/dd/yyyy}# AND [Suggestion Date] <= #{1:M/dd/yyyy}#", StartDate, EndDate);
}
else if (string.IsNullOrEmpty(SearchEmp) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("Employee like '%{0}%'", SearchEmp.Trim().Replace("'", "''"));
}
else if (string.IsNullOrEmpty(SearchSupv) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Supervisor] like '%{0 }%'", SearchSupv.Trim().Replace("'", "''"));
}
else if (string.IsNullOrEmpty(SearchAssigned) == false)
{
employeeSuggestionsBindingSource.Filter = string.Format("[Assigned To] like '%{0}%'", SearchAssigned.Trim().Replace("'", "''"));
}
else if (comboBoxCompleted.Text == "Incomplete")
{
employeeSuggestionsBindingSource.Filter = string.Format("[Completed]='False'");
}
else if (comboBoxCompleted.Text == "Completed")
{
employeeSuggestionsBindingSource.Filter = string.Format("[Completed]='True'");
}
There has to be a much easier way to filter the results and I know I'm probably doing it in the worst way...ha.
If I understand you correctly, you want to build up your filter criteria with one or more predicates. You can do this by composing multiple conditions together with AND:
string filter = null;
if (StartDate < EndDate)
{
filter = CombineCriteria(
filter,
string.Format(
"[Suggestion Date] >= #{0:M/dd/yyyy}# AND " +
"[Suggestion Date] <= #{1:M/dd/yyyy}#",
StartDate,
EndDate));
}
if (string.IsNullOrEmpty(SearchEmp) == false)
{
filter = CombineCriteria(
filter,
string.Format(
"[Employee] LIKE '%{0}%'",
SearchEmp.Trim().Replace("'", "''")));
}
// ... more filter conditions ...
if (comboBoxCompleted.Text == "Incomplete")
filter = CombineCriteria(filter, "[Completed] = False");
else if (comboBoxCompleted.Text == "Completed")
filter = CombineCriteria(filter, "[Completed] = True");
employeeSuggestionsBindingSource.Filter = filter;
Where CombineCriteria() is as follows:
private static string CombineCriteria(string oldCondition, string newCondition) {
if (string.IsNullOrEmpty(oldCondition))
return newCondition;
return "(" + oldCondition+ ") AND (" + newCondition + ")";
}

Categories

Resources