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)}
Related
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
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
}
How do I sort on multiple columns? I tried using this expression:
if (name != null)
{
if (name.Equals(SortEnum.ASC))
{
employees = employees.OrderBy(e => e.Name);
}
else if (name.Equals(SortEnum.DESC))
{
employees = employees.OrderByDescending(e => e.Name);
}
}
if (surname != null)
{
if (surname.Equals(SortEnum.ASC))
{
employees = employees.OrderBy(e => e.Surname);
}
else if (surname.Equals(SortEnum.DESC))
{
employees = employees.OrderByDescending(e => e.Surname);
}
}
But only the last column becomes sorted. Somewhere I saw method ThenBy(), but I don't have it.
Please help.
using System.Linq.Dynamic
List<string> orderstr = new List<string>();
orderstr.Add((name != null)? name.Equals(SortEnum.ASC)? "Name ASC": "Name DESC" : string.Empty);
orderstr.Add((surname != null)? surname.Equals(SortEnum.ASC)? "Surname ASC": "Surname DESC" : string.Empty);
var reslt = employees.OrderBy(string.Join(", ",orderstr.Where(x=>!string.IsNullOrEmpty(x))));
How can i factorize this code?
my filter returns several type of document. the difficult is that i have some query per type... i would like a generic method to return a correct query
thanks
if(this.comboBoxType.Text.Equals("Vente"))
{
IQueryable<Vente> queryV = ContexteDAO.ContexteDonnees.Vente
.Include("Client")
.Include("Paiement")
.Include("Employe").OrderBy(v => v.venteID);
if (this.tbxNomCli.Text != "")
queryV = queryV.Where(v => v.Client.nom.Contains(this.tbxNomCli.Text));
if (this.comboBoxEtat.Text != "Tous")
queryV = queryV.Where(v => v.etat == this.comboBoxEtat.Text);
if (this.checkBoxDate.Checked)
queryV = queryV.Where(v => v.date.Equals(this.dateTimePicker.Value.Date));
if (this.tbxTva.Text != "")
queryV = queryV.Where(v => v.Client.numEntreprise.Contains(this.tbxTva.Text));
if (this.checkBoxVendeur.Checked)
{
Employe employe = this.comboBoxVendeur.SelectedItem as Employe;
queryV = queryV.Where(v => v.Employe.login.Equals(employe.login));
}
this.documentBindingSource.DataSource = queryV.ToList();
}
if (this.comboBoxType.Text.Equals("Commande"))
{
IQueryable<Commande> queryC = ContexteDAO.ContexteDonnees.Commande
.Include("Client")
.Include("Paiement")
.Include("Employe").OrderBy(c => c.commandeID);
if (this.tbxNomCli.Text != "")
queryC = queryC.Where(v => v.Client.nom.Contains(this.tbxNomCli.Text));
if (this.comboBoxEtat.Text != "Tous")
queryC = queryC.Where(v => v.etat == this.comboBoxEtat.Text);
if (this.checkBoxDate.Checked)
queryC = queryC.Where(v => v.date.Equals(this.dateTimePicker.Value.Date));
if (this.tbxTva.Text != "")
queryC = queryC.Where(v => v.Client.numEntreprise.Contains(this.tbxTva.Text));
if (this.checkBoxVendeur.Checked)
{
Employe employe = this.comboBoxVendeur.SelectedItem as Employe;
queryC = queryC.Where(v => v.Employe.login.Equals(employe.login));
}
this.documentBindingSource.DataSource = queryC.ToList();
}
You could make a generic approach:
public IQueryable<T> GetData<T>( string identifier )
{
switch( identifier )
{
case "Vente":
{
return ContexteDAO.ContexteDonnees.Vente
.Include("Client")
.Include("Paiement")
.Include("Employe")
.OrderBy(v => v.venteID);
// do more stuff
break;
}
// add more cases
default:
{
return null;
}
}
}
the call would look like:
IQueryable<Vente> result = GetData<Vente>( "Vente" );
it would solve your problem but i won't like it, because you need to specify the type AND need an identifier which selection you would like to perform. This could lead to an exception really fast when you have something like GetData<Vente>( "OtherEntity" ).
Whenever I access my page directly (mypage.aspx) it returns an error:
Object not set to object not set to an instance of an object.
If I add a querystring (mypage.aspx?sr=true) it works but I am checking to make sure that before it evaluates that it has a value, and it should not have a value. So why am I getting the error when I access the page directly?
if (!IsPostBack)
{
string qu1 = "";
string qu2 = "";
string qu3 = "";
if (Request.QueryString["qu1"] != null)
{
qu1 = Request.QueryString["qu1"].ToString();
if (qu1 != "")
{
qu1DropDownList.SelectedValue = industry;
}
}
if (Request.QueryString["qu2"] != null)
{
qu2 = Request.QueryString["qu2"].ToString();
if (qu2 != "")
{
qu2DropDownList.SelectedValue = category;
}
}
fillDropDownList();
if (Request.QueryString["qu3"] != null)
{
qu3 = Request.QueryString["qu3"].ToString();
if (qu3 != "")
{
qu3tDropDownList.SelectedValue = product;
}
}
}
string search = "";
string qu1value = IndustryDropDownList.SelectedValue;
string qu2value = ProductCategoryDropDownList.SelectedValue;
string qu3value = ProductDropDownList.SelectedValue;
using (SPSite site = new SPSite("SITE"))
using (SPWeb oWebsiteRoot = site.OpenWeb())
{
SPList oList = oWebsiteRoot.Lists["SpacesInfo"];
SPListItemCollection items = null;
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
{
search = Request.QueryString["sr"].ToString();
if (search == "true")
{
if (indvalue == "select" & catvalue == "select")
{
items = oList.Items;
}
else if (indvalue != "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Industry' /><Value Type='Choice'>" + indvalue +
"</Value></Eq></Where>";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else
{
errorLabel.Text = "Please contact the administrator.";
items = oList.Items;
}
}
else
{
items = oList.Items;
}
}
DataTable table = new System.Data.DataTable();
table = items.GetDataTable();
spacerepeater.DataSource = table;
spacerepeater.DataBind();
}
Change the order of this if statement:
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
should be
if (Request.QueryString["sr"] != null && Request.QueryString["sr"] != "")
The issue is this, in your code it looks for the empty string ("") and fails because the object is null. In my version it will see the value is null and fail out of the if statement without checking the second one.
This is often called short circuit evaluation.
ref http://en.wikipedia.org/wiki/Short-circuit_evaluation
Use:
if (!String.IsNullOrEmpty(Request.QueryString["sr"]))
{
//Do stuff
}