queries in entity framework - asp.net

i have to fetch those records where cityname like'zipcode' where zipcode is variable and apply conditions
var zipcd = (from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select u).ToList().Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 1)
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else if (locations == "")
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName + "," + locations;
}
if (zipcd.Count() > 3) is greater than 3
{
locations = locations.Replace(locations, "," + "<br>");
}

The problem is that you're casting an iterator to the type of a single element on the line
ViewSearch vs = (ViewSearch)zipcd.
If you want vs to be a single object, you must call First() or FirstOrDefault() on your collection:
ViewSearch vs = zipcd.First(); // Throws if there are no elements
ViewSearch vs = zipcd.FirstOrDefault(); // null if there are no elements

First of all I would suggest that you download and use the lovely LINQPad not only to run your LINQ queries first but also to learn from it (has a lot of samples that you can run right form there, no more config needed)
for your question:
var zipcd = (
from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct().ToList();
As you can see the query works:

Distinct at the end of your query uses IEqualityComparer, and I'm guessing you haven't defined one for Viewsearch. It would look something like this:
public class ViewsearchComparer : IEqualityComparer<Viewsearch>
{
public bool Equals(Viewsearch vs1, Viewsearch vs2)
{
// Implementation
}
public int GetHashCode(Viewsearch vs)
{
// Implementation
}
}
After you have that defined, you pass it into your distinct call:
.Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
Stateabbr = u.StateAbbr
})
.Distinct(new ViewsearchComparer());

Related

How to correctly return from stored procedure in Sql to model?

I need to return list of values from stored procedure to my model. How do I do it:
[HttpGet("{id}")]
public DataSource Get(int id)
{
DataSource ds = _dbContext.DataSources.Where(d => d.Id == id)
.Include(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions).FirstOrDefault();
foreach(DataSourceParam p in ds.DataSourceParams)
{
if(p.TypeId == 5)
{
p.SelectOptions = _dbContext.SelectOptions.FromSql("Exec " + ds.DataBaseName + ".dbo." + "procGetTop50 " + ds.Id + ", 1").ToList();
}
}
return ds;
}
First, declare your procedure with parameters:
string sql = "myProcedure #param1, #param2";
Second, create parameters
var param1 = new SqlParameter { ParameterName = "param1", Value = param1Value};
var param2 = new SqlParameter { ParameterName = "param2", Value = param2Value };
Finally, exec the code:
info = this.DbContext.Database.SqlQuery<MyModel>(sql, param1, param2).FirstOrDefault();
This is it!
Just remember your model must match with the procedure columns. With means, if your procedure returns a column named 'MyProp' your model 'MyModel' must have a 'MyProp' property.

asp:calendar binds last value to date from database

I have to bind an <asp:calendar> with data fetched from a database using a linq query.
Here is the linq code
public List<AllCalander> SearchCalender(int month, int zip, string type, int cause)
{
var xyz = (from m in DB.Calenders
where(m.DateFrom.Value.Month==month || m.Zip==zip || m.ActivityType==type || m.CauseID==cause)
group m by new { m.DateFrom } into grp
select new
{
caustitle = grp.Select(x => x.Caus.CauseTitle),
datfrm = grp.Key.DateFrom,
total = grp.Count()
})
.ToList()
.Select(m => new AllCalander
{
DateFrom =Convert.ToDateTime(m.datfrm),
CauseTitle = string.Join(",", m.caustitle),
Total = m.total
});
My aspx.cs code is here
List<AllCalander> calnder = calbll.SearchCalender(mnth,ZipString,type,causeString);
foreach (var myItem in calnder)
{
string datetime = myItem.DateFrom.ToString();
Literal myEventNameLiteral = new Literal();
myEventNameLiteral.ID = i + myItem.CauseID.ToString();
// string currentcalanderDate = e.Day.Date.Day.ToString() ;
if (string.Equals(DateTime.Parse(datetime).ToString("MMM dd yyyy"), e.Day.Date.ToString("MMM dd yyyy")))
{
string a = myItem.CauseTitle;
if (a != cause)
cause = a;
coun++;
myEventNameLiteral.Mode = LiteralMode.PassThrough;
myEventNameLiteral.Text = "<br /><span style='font-family:verdana; font-size:10px;'>" + myItem.CauseTitle + "(" + myItem.Total + ")"+ " ";
e.Cell.Controls.Add(myEventNameLiteral);
}
i++;
}
but on output it only shows the last value from database instead of showing all the data.
Can somebody please tell me what's wrong?
Thanks in advance
group m by new { m.DateFrom, m.Caus.CauseTitle } into grp

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

input string was not in correct format asp.net

I have a strange error. I have a page which loads values according to the country value stored in the session. it works fine for all other countries. only for particular country it is returning this error.
protected void populateDDMonth()
{
int numberOfMonths;
string monthName;
string completeCalendarFile = Path.Combine(Request.PhysicalApplicationPath + "admin\\text-files\\", calendarFile);
TextReader tr = new StreamReader(completeCalendarFile);
date_classa = tr.ReadLine(); //Get classa end date string
date_classb = tr.ReadLine(); //Get classb end date string
DateTime dateConvert_classa = DateTime.Parse(date_classa);
DateTime dateConvert_classb = DateTime.Parse(date_classb);
tr.Close();
DataTable MonthTable = new DataTable();
MonthTable.Columns.Add("Month", typeof(string));
MonthTable.Columns.Add("Date", typeof(string));
DateTime endMonth = DateTime.Today;
DDMonth.Items.Clear(); //Clear dropdown in order to re-populate
string classValue = DDClassType.SelectedValue.ToString();
if (classValue == "10" || classValue == "12" || classValue == "15")
{
endMonth = dateConvert_classa;
}
else if (classValue == "9" || classValue == "13" || classValue == "16")
{
endMonth = dateConvert_classb;
}
if (endMonth.Year > DateTime.Today.Year)
{
numberOfMonths = (endMonth.Month + 12) - DateTime.Today.Month;
}
else
{
numberOfMonths = endMonth.Month - DateTime.Today.Month;
}
for (int i = 0; i < numberOfMonths + 1; i++)
{
monthName = DateTime.Now.AddMonths(i).ToString("MMM"); //Display month as 3 letter string
DataRow MonthRow = MonthTable.NewRow();
MonthRow[0] = monthName.ToString() + " " + DateTime.Now.AddMonths(i).Year.ToString();
MonthRow[1] = DateTime.Now.AddMonths(i).ToString();
DDMonth.Items.Add(new ListItem(monthName.ToString() + " " + DateTime.Now.AddMonths(i).Year.ToString(),
DateTime.Now.AddMonths(i).ToString()));
}
if (Session["selectedMonth"] != null)
{
DDMonth.SelectedValue = Session["selectedMonth"].ToString();
}
if (!Page.IsPostBack)
{
DateTime startingDate = DateTime.Parse(DDMonth.SelectedValue.ToString());
LbCalendarCurrentMonth.Text = startingDate.ToString("MMMM");
}
}
This is a common problem with int casts and conversions within the International cultures:
http://support.microsoft.com/kb/942460
Whatever value is selected (if any) in DDMonth drop down, is not a valid date.
So the following code should work without error:
DateTime startingDate;
if (DateTime.TryParse(DDMonth.SelectedValue.ToString(), out startingDate)
{
LbCalendarCurrentMonth.Text = startingDate.ToString("MMMM");
}

Resources