LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method - linq

var query = from d in db.mytable
where d.Code == int.Parse(WebUtils.GetQueryString("Code"))
orderby d.PersonInfo
select d;
i get the following error
LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.
i have tried to rewrite the int.Parse(WebUtils.GetQueryString("Code")) like this
int intCode = int.TryParse(WebUtils.GetQueryString("OfferCode"));
but still got an error

Just parse your query string outside of the query context:
int code = int.Parse(WebUtils.GetQueryString("Code"));
var query = from d in db.mytable
where d.Code == code
orderby d.PersonInfo
select d;

You can convert the 'Code' field to string instead of the query string to int.
This should works:
var queryString = WebUtils.GetQueryString("Code");
var query = from d in db.mytable
where SqlFunctions.StringConvert(d.Code) == queryString
orderby d.PersonInfo
select d;
There is no way to convert the string to int. EF doesn't know how to translate that to SQL if you use int.Parse

Related

Get Date part Using LINQ

I have four tables, with Date data type for the fields startingDate, EndingDate, and ApplyingDate.
I am using ADO.net Entity Framework.
I have written the following query to get the results, but I am getting the dates with the time, and I want only the date part.
I have used EntityFunctions.TuncateTime, but I am still getting same results.
Could anyone please suggest me, how to Get the date only ?
var leaveList = (from application in db.tbl_ApplicationData
join employee in db.tbl_EmployeeDetails
on application.UserName equals employee.UserName
join leaveType in db.tbl_LeaveType
on application.LeaveTypeId equals leaveType.LeaveTypeId
join status in db.tbl_Status
on application.ApplicationStatusId equals status.StatusId
where application.UserName == "100083"
select new
{
EmployeeName = employee.EmployeeName,
LeaveTypeID = leaveType.LeaveTypeName,
StartingDate = EntityFunctions.TruncateTime(application.StartingDate),
EndingDate = EntityFunctions.TruncateTime(application.EndingDate),
AppliedDate = EntityFunctions.TruncateTime(application.ApplyingDate),
NoOfDays = application.NoOfDays,
LeavePurpose = application.LeavePurpose,
LeaveStatus = status.StatusName
});
If your entity model is a System.DateTime, you can just use the DateTime methods when you are using your object:
select new {
EndingDate = application.EndingDate
};
var myValue = leaveList.EndingDate.Date;
Or if you want a string:
leaveList.EndingDate.ToShortDateString()

What is the difference between these two linq queries? The first one will not work. The second will. Why?

I have my code using the following linq:
var consulta = from grupo in Contexto.Set<GRUPOCONTRATO>()
join detalhe in Contexto.Set<GRUPOCONTRATODETALHE>()
on grupo.CDGRUPOCONTRATO equals detalhe.CDGRUPOCONTRATO
where grupo.NOGRUPOCONTRATO.Contains("FACIL")
&& detalhe.NRCONTRATO == carteira.NumeroDoContrato
select detalhe;
PlanoFacil = consulta.Any();
The code above wont work and throws an exception like this:
Object of type 'System.Data.Objects.ObjectQuery1[Dominio.PERICIA]' cannot be converted to type 'System.Data.Entity.IDbSet1[Dominio.PERICIA]'.
Please note that it points to a problem with another entity (PERICIA) which has nothing to do with the query and has no relationship with the two entities in the query...
But if I split the query like this it works:
var consulta = from grupo in Contexto.Set<GRUPOCONTRATO>()
join detalhe in Contexto.Set<GRUPOCONTRATODETALHE>()
on grupo.CDGRUPOCONTRATO equals detalhe.CDGRUPOCONTRATO
where grupo.NOGRUPOCONTRATO.Contains("FACIL")
//&& detalhe.NRCONTRATO == carteira.NumeroDoContrato
select detalhe;
PlanoFacil = consulta.Any(detalhe => detalhe.NRCONTRATO == carteira.NumeroDoContrato);
Why?

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IQueryable'

I want to define a function containing a Linq query as bellow:
public IQueryable GetBasket(Guid userId)
{
DabbaghanDataContext db = new DabbaghanDataContext();
int rowNo = 0;
var query = (from c in db.Carts
join co in db.CartOrders on c.Id equals co.Cart_Id
join p in db.Products on co.Product_Id equals p.Id
where c.UserId == userId && c.Issued == false
select new
{
co.Quantity,
co.TotalPrice,
p.Code,
p.Price,
p.Thumbnail
}).AsEnumerable().Select(r => new
{
RowNumber = ++rowNo,
Quantity = r.Quantity,
TotalPrice = r.TotalPrice,
Code = r.Code,
Price = r.Price,
Thumbnail = r.Thumbnail
});
return query;
}
I get error
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'.
on the return query line.
What is the problem? How can I solve this problem? Please help.
Your problem is the call to AsEnumerable- It converts the IQueryable to a IEnumerable; and therefore, you cannot return it as an IQueryable.
Correct me if I am wrong, but the second select seems to only add the row number to the result. You might as well want to do that together with the initial select, and skip the call to AsEnumerable().
Possible solutions: Rewrite the query to not use AsEnumerable (if you want an IQueryable returned), or you could change the return type to be IEnumerable, if that is a better fit for your problem.
In return query; change that to return query.AsQueryable();
And also try to change the method signature to use IQueryable instead of the nongeneric one

Linq conversion

I am using the following code to return an IList:
public IList<string> FindCodesByCountry(string country)
{
var query = from q in session.Linq<Store>()
where q.Country == country
orderby q.Code
select new {q.Code};
return (IList<string>) query.ToList();
}
However I keep getting this error:
Unable to cast object of type 'System.Collections.Generic.List1[<>f__AnonymousType01[System.String]]' to type 'System.Collections.Generic.IList`1[System.String]'.
What I am supposed to return here?
as long as q.code is a string this should work:
note that it is not creating an anonymous object, just the string is being selected.
public IList<string> FindCodesByCountry(string country)
{
var query = from q in session.Linq<Store>()
where q.Country == country
orderby q.Code
select q.Code;
return query.ToList();
}
Is there a reason you were selecting an anonymous type? If not try this...
var query = from q in session.Linq<Store>()
where q.Country == country
orderby q.Code
select q.Code;
How about
query.Select(s => s.ToString()).ToList();
Or
query.Cast<String>().ToList();
But I'm assuming that q.Code is a string? In which case you just want to change your LINQ expression:
var query = from q in session.Linq<Store>()
where q.Country == country
orderby q.Code
select q.Code;
In the query, instead of selecting an anonymous class containing a string, just select the string itself:
var query = from q in session.Linq<Store>()
where q.Country == country
orderby q.Code
select q.Code;
You can't cast a list of custom types to a list of strings like that. The easiest way would be to have your query object begin it's life as an iEnumerable list of strings, rather than a custom type. Change your select line to:
select new q.Code.toString();
and you'll be good. If q.Code is itself a string to begin with, then the .ToString() won't be necessary.
Try this:
return query.ToList<string>();

What is the correct way of reading single line of data by using Linq to SQL?

I'm very new to Linq, I can find multi-line data reading examples everywhere (by using foreach()), but what is the correct way of reading a single line of data? Like a classic Product Detail page.
Below is what I tried:
var q = from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate };
string strProductName = q.First().ProductName.ToString();
string strProductDescription = q.First().ProductDescription.ToString();
string strProductPrice = q.First().ProductPrice.ToString();
string strProductDate = q.First().ProductDate.ToString();
The code looks good to me, but when I see the actual SQL expressions generated by using SQL Profiler, it makes me scared! The program executed four Sql expressions and they are exactly the same!
Because I'm reading four columns from a single line. I think I must did something wrong, so I was wondering what is the right way of doing this?
Thanks!
Using the First() extension method would throw the System.InvalidOperationException when no element in a sequence satisfies a specified condition.
If you use the FirstOrDefault() extension method, you can test against the returned object to see if it's null or not.
FirstOrDefault returns the first element of a sequence, or a default value if the sequence contains no elements; in this case the default value of a Product should be null. Attempting to access the properties on this null object will throw ArgumentNullException
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }).FirstOrDefault();
if (q != null)
{
string strProductName = q.ProductName;
string strProductDescription = q.ProductDescription;
string strProductPrice = q.ProductPrice;
string strProductDate = q.ProductDate;
}
Also, you shouldn't have to cast each Property ToString() if you're object model is setup correctly. ProductName, ProductDescription, etc.. should already be a string.
The reason you're getting 4 separate sql queries, is because each time you call q.First().<PropertyHere> linq is generating a new Query.
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }
).First ();
string strProductName = q.ProductName.ToString();
string strProductDescription = q.ProductDescription.ToString();
string strProductPrice = q.ProductPrice.ToString();
string strProductDate = q.ProductDate.ToString();

Resources