Conversion error with Entity and Linq - linq

I got the error
cannot implicity convert type 'System.Linq.IQueryable<EntityNetimoveis.San_Imovel>' to 'EntityNetimoveis.San_Imovel' An Explicit conversion exists (are you missing a cast ?)
This occurs when I try the following code
EntityNetimoveis.San2011Entities db = new EntityNetimoveis.San2011Entities();
EntityNetimoveis.San_Imovel im = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
What type of conversion I have to do ?

EntityNetimoveis.San_Imovel im = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
The type of im is an IQueryable<EntityNetimoveis.San_Imovel> because you are running a where query and there might be more than one result. If you want the first result matching your query you should use .FirstOrDefault(). Try changing you code as:
EntityNetimoveis.San_Imovel im = db.San_Imovel.FirstOrDefault(a => a.Credenciada_Id == 10);
If you want to return more than one entity and process them, lets say using a foreach loop, then you need to change the type of the return value to IEnumerable<Netimoveis.San_Imovel>. See the following example:
IEnumerable<EntityNetimoveis.San_Imovel> ims = db.San_Imovel.Where(a => a.Credenciada_Id == 10);
The you can use the following:
foreach(var im in ims) {
// your code goes here
}

If the lambda can return more than one record:
var imList = db.San_Imovel.Where(a => a.Credenciada_Id == 10).ToList();

Related

Error getting items from Entity Framework using Lambda query

I have a listbox that I am trying to populate with the result of a SQL Server query via a Entity Framework linq/lambda query. I am feeding the query with a value from a combobox. I keep getting lot of errors like the following: Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Any suggestions on how to fix this? I just want two fields to populate in a grid
var pAt = ent.Patterns.Where(p => p.Case_Id == (cbCase.SelectedItem as Case).Case_Id).Select(x => new Pattern{ PatternID = x.PatternID, Pattern1 = x.Pattern1 });
listBox1.DataSource = pAt;
listBox1.ValueMember = "PatternID";
listBox1.DisplayMember = "Pattern1";
Try this instead :
var pAt = ent.Patterns.AsEnumerable()
.Where(p => p.Case_Id == ((Case)cbCase.SelectedItem).Case_Id)
.Select(x => new Pattern{ PatternID = x.PatternID, Pattern1 = x.Pattern1 });
Hope this will fix your issue.
Separate the code parts from the SQL parts. Entity Framework can't necessarily construct an SQL query using code objects, but you can usually work around it. Eg:
var caseId = (cbCase.SelectedItem as Case).Case_Id;
var pAt = ent.Patterns.Where(p => p.Case_Id == caseId)
.ToArray()
.Select(x => new Pattern { PatternID = x.PatternID, Pattern1 = x.Pattern1 });

LINQ read Select values

I have a LINQ query where I want to select and read the p.Api value.
var api = DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api);
How do I read the p.Api value?
I have tried api.ToString() but I get SQL instead of actual column value.
You are getting an IEnumerable<> back (and your ToString call is showing you the value of that expression).
If you are expecting a single value, do this:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api)
.Single();
You might be interested to read about the other methods like Single(): SingleOrDefault, First, FirstOrDefault. Which one you used depends on whether you are expecting a single or multiple values returned (Single vs. First) and what you want to happen if there are no values (the *Default methods will return the type default instead of throwing an exception).
Or if you want to look at all the returned values:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api);
foreach (var apiValue in api)
{
// apiValue will have the value you're looking for.
}
Try this snippet of code:
string apiValue = api.FirstOrDefault().ToString();
your syntex seems ok..
By the way try this
string api =DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api).FirstOrDefault();
if p.Ip is a unique key in your table you could try to add .FirstOrDefault() after your Linq query.
public string getselectedvalue(ListBox l)
{
string vtext="",vval="";
var selectedQueryText = l.Items.Cast<ListItem>().Where(item => item.Selected);
var selectedQueryVal = l.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value);
vtext= String.Join("','", selectedQueryText ).TrimEnd();
vval= String.Join("','", selectedQueryVal ).TrimEnd();
return v;
}

Better way to check resultset from LINQ projection than List.Count?

Is there a better way to check if a LINQ projection query returns results:
IList<T> TList = db.Ts.Where(x => x.TId == 1).ToList(); // More canonical way for this?
if (TitleList.Count > 0)
{
// Result returned non-zero list!
string s = TList.Name;
}
You can use Any(), or perhaps more appropriately to your example, SingleOrDefault(). Note that if you are expecting more than one result and plan to use all of them, then it doesn't really save anything to use Any() instead of converting to a List and checking the length. If you don't plan to use all the results or you're building a larger query that might change how the query is performed then it can be a reasonable alternative.
var item = db.Ts.SingleOrDefault( x => x.TId == 1 );
if (item != null)
{
string s = item.Name;
...
}
or
var query = db.Ts.Where( x => x.Prop == "foo" );
if (query.Any())
{
var moreComplexQuery = query.Join( db.Xs, t => t.TId, x => x.TId );
...
}

Could not resolve property for Average linq to NHibernate mapped object

I have code that calculate average number of days from date opened to date closed.
When i run the expression using Linq and lambda expression i get error as follows:
Error message: could not resolve property: DateClosed.DateCreated of:
TestProject.LegalWork
where code is:
var result = Repository.All
.Where(x => x.DateClosed != null)
.Average(x => ((DateTime)x.DateClosed - x.DateCreated).TotalDays);
How ever when i run this using loop and filter on condition only, eveything work fine.
int number= 0;
decimal totalDays = 0;
foreach (LegalWork legalWork in Repository.All.Where(x => x.DateClosed != null))
{
totalDays += (decimal)((DateTime)legalWork.DateClosed - legalWork.DateCreated).TotalDays;
number++;
}
return (totalDays == 0 || numberOfLegalWork ==0 ) ? 0 : Convert.ToDecimal(totalDays/numberOfLegalWork);
What is wrong in Linq and Lambda version?
I'm sure you can't call to:
x.DateClosed - x.DateCreated
or givenDate.TotalDays in linq2nhibernate, because you should call a specific function of DateTime which is not part of linq2nhibernate it's part of .net framework and it doesn't implemented in linq2nhibernate, but your current error message says another thing, to solve ur problem currently u can do:
var result = Repository.All.Where(x => x.DateClosed != null).ToList()
.Average(x => ((DateTime)x.DateClosed - x.DateCreated).TotalDays);
if there is problem with above code, please insert ur class definition,
but sure it's not a best solution, it's better to write a stored procedure and call it.

LINQ: Field is not a reference field

I've got a list of IQueryable. I'm trying to split this list into an array of IQueryable matching on a certain field (say fieldnum) in the first list...
for example, if fieldnum == 1, it should go into array[1]. I'm using Where() to filter based on this field, it looks something like this:
var allItems = FillListofMyObjects();
var Filtered = new List<IQueryable<myObject>(MAX+1);
for (var i = 1; i <= MAX; i++)
{
var sublist = allItems.Where(e => e.fieldnum == i);
if (sublist.Count() == 0) continue;
Filtered[i] = sublist;
}
however, I'm getting the error Field "t1.fieldnum" is not a reference field on the if line. stepping through the debugger shows the error actually occurs on the line before (the Where() method) but either way, I don't know what I'm doing wrong.
I'm farily new to LINQ so if I'm doing this all wrong please let me know, thanks!
Why don't you just use ToLookup?
var allItemsPerFieldNum = allItems.ToLookup(e => e.fieldnum);
Do you need to reevaluate the expression every time you get the values?
Why not use a dictionary?
var dictionary = allItems.ToDictionar(y => y.fieldnum);

Resources