sequence contains no matching element but it contains element when I insert a break point - c#-3.0

I have this code:
int gts_size=20;
int gts_type=1;
var r = from room in collection_of_rooms.rooms
where gts_size <= room.capacity_of_room
select room;
var r2 = r.First<Room>(rr => (rr.room_type == gts_type)); // here is the error
rooms is array of class "Room" , which has fields: capacity_of_room and room_type
exception thrown with message "sequence contains no matching element"
but when I insert a break point to trace the code, it works properly and r1,r2 have values.
I have tried FirstOrDefault() and the same is still happening.
Can any one help me please?

Related

Entity Framework, Linq : concatenating results from child table

I have an existing linq query which gets some data into a view model object. This is working fine.
I want to add a new property for data from child table which will have column values from a child table in a comma separated string format.
Problem: I am not able to concatenate the results using string.join
Simplified version of tables showing only relevant fields
part
id
part number
1
ABC1
2
DEF1
vendor
id
vendorname
1
acme
2
john
vendor part name (vendor specific part number)
partid
vendorid
partname
1
1
GDSE-553-32
1
2
JWWVV-HH-01
simplified version of query
result = (from p in DBContext.Parts.Where(w => w.EquipmentId == eId)
select new PartModel
{
Id = p.Id,
Number = p.PartNumber,
VendorPartNames= String.Join(",", DBContext.VendorPartName.Where(w => w.PartId == p.Id).Select(s => s.PartName))//this line causes exception (shown below)
});
Exception:
LINQ to Entities does not recognize the method 'System.String Join(System.String, System.String[])' method, and this method cannot be translated into a store expression.
Please note: the actual query has some joins and other columns, so please dont suggest solutions that requires joins.
If I change the "VendorPartName" to a List type , I can get the results without any problems.
My only problem is in "How to convert the results for "VendorPartName" property to a comma separated strings?"
eg: based on sample table data provided, it should be
GDSE-553-32, JWWVV-HH-01
Entity Framework does not support String.Join() method.
So, what we can do is to fetch VendorPartNames as a string collection and then we can later separate it with ,.
Note: For this, we would first use an anonymous object and later convert it to PartModel.
So your query would look like this:
var parts = DBContext.Parts
.Where(w => w.EquipmentId == eId)
.Select(p => new {
Id = p.Id,
Number = p.PartNumber,
VendorPartNames = p.VendorPartName.Select(n => n.PartName)
}).ToList();
var result = parts.Select(i => new PartModel {
Id = i.Id,
Number = i.Number,
VendorPartNames = String.Join(",", i.VendorPartNames)
}).ToList();

sqflite IN operator with AND operator

I have following query which select from employee table where name is "max" and ID not in 123 and 444.
Not in IDs can grow in future. But I am receiving error as
Error
( 8023): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: DatabaseException(near "?": syntax error (code 1 SQLITE_ERROR): , while compiling:
Query
List<String> a = [];
a.add("123");
a.add("444");
var table = await mydb.rawQuery(
"SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC",
["max", a]);
If the LIST is unpredictable, one way is that you can use JOIN to create your select statement with required value of NOT IN. Below is one sample.
void main() {
List<String> a = [];
a.add("123");
a.add("444");
var select =
'SELECT value from employee WHERE employeename = ? AND id NOT IN (\'' +
(a.join('\',\'')).toString() +
'\') ORDER BY timestamp DESC';
var table = await mydb.rawQuery(select, ["max"]);
}
If you print the variable select you will get
SELECT value from employee WHERE employeename = ? AND id NOT IN ('123','444')
ORDER BY timestamp DESC.
Then you can pass the above statement to rawquery and get your result.
P.S:Use your single quote and double quote accordingly.
I'd go for #arun-palanisamy 's solution, see his comment. Props go to him. I just tried the following -- with Groovy/Postgres, but the error seems to be the same, so you might want to give it a try:
String[] a = ['123', '444']
// your code, throws 'ERROR: syntax error at or near "$2"':
// def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC", ["max", a])
// code of arun-palanisamy, compiles:
def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN (${a.join(', ')}) ORDER BY timestamp DESC", ["max", a])
Side notes:
You might want to try a different type for a, such as Array in my code, or even a HashMap.
There are examples (like here) where the number of ? are generated dynamically.
Update: Go for this answer, we posted simultaneously

Get the next item in lambda expression

I checked the answered questions but none of them address the issue I have.
I just need to get the NEXT ITEM from the table Cars (sql server database) and I have the following query against the EF which kinda ignores the Skip:
var carid = value;
var car = db.Cars.Where(c => c.CarID == carid).OrderBy(c => c.CarID).Skip(1).FirstOrDefault();
Response.Write(car.CarID);
It always returns the very same element as initial value. I guess firstordefault is not the way to go.
Thank you
The Correct code is probably
var carid = value;
var car = db.Cars.Where(c => c.CarID > carid).OrderBy(c=> c.CarID).FirstOrDefault();
//needs a null check before using car
Response.Write(car.CarID);
(note the > in the where)
However the fact that your previous code did return a value (as opposed to null) means that you have multiple records with the same CarID. This seems wrong.
Also note that the proper code requires autoincrementing IDs in the database.

Linq to Entity - Explanation/Advice on behaviour Where() vs Where().ToList() in foreach loop

So the scenario in a nutshell: I have an entity (EF4) that has a foreign key to the primary key in the same entity (hierarchical structure) e.g.
MyEntityId (Primary Key)
ParentMyEntityId (Foreign key to Primary Key)
If I have a MyEntityList List<MyEntity> where the EntityState for both is Unchanged:
entity 1 - {MyEntityId = 10, ParentMyEntityId = null}
entity 2 - {MyEntityId = 11, ParentMyEntityId = 10}
and then I do this:
//Initially has 2 items in 'in' clause - iterates once and then exits because the EntityState of the second item has changed to Modified
foreach(MyEntity m in MyEntityList.Where(e => e.EntityState == System.Data.EntityState.Unchanged))
{
db.DeleteObject(m);
}
The first MyEntity is deleted, but the second changes to "Modified" and the foreach doesn't run a second time - I'm guessing due to the foreign key constraint.
However if I do:
//Iterates twice, even though the EntityState of the second item has changed to Modified
foreach(MyEntity m in MyEntityList.Where(e => e.EntityState == System.Data.EntityState.Unchanged).ToList())
{
db.DeleteObject(m);
}
Both entities are deleted (which is the desired effect).
Whilst I have a solution, I'm interested in why this happens, I was always under the impression that the iterator "set" that was defined at the start of the foreach loop remained the same, or threw a runtime error if you tried to modify it.
Should I not be using Where? Is there a better way to do this?
The iterator set is defined before the loop runs because you execute ToList (if you didn't do this it wouldn't be well defined).
So the iteration source is constant. But not the object you iterate over. The object references you get are constant but not the objects pointed to by them.
The version without ToList is equivalent to:
foreach(MyEntity m in MyEntityList) //always 2 items
{
//loop body always called two times
if (e.EntityState == System.Data.EntityState.Unchanged) //2 times
db.DeleteObject(m); //1 time
}
The ToList-version is equivalent to:
var copy = MyEntityList.Where(e => e.EntityState == System.Data.EntityState.Unchanged).ToList(); //always 2 items
foreach(MyEntity m in copy)
{
//loop body always called two times
db.DeleteObject(m); //2 times
}

Entity Framework: selecting from multiple tables

I have a statement:
var items = from e in db.Elements
join a in db.LookUp
on e.ID equals a.ElementID
where e.Something == something
select new Element
{
ID = e.ID,
LookUpID = a.ID
// some other data get populated here as well
};
As you can see, all I need is a collection of Element objects with data from both tables - Elements and LookUp. This works fine. But then I need to know the number of elements selected:
int count = items.Count();
... this call throws System.NotSupportedException:
"The entity or complex type 'Database.Element' cannot be constructed in a LINQ to Entities query."
How am I supposed to select values from multiple tables into one object in Entity Framework? Thanks for any help!
You are not allowed to create an Entity class in your projection, you have to either project to a new class or an anonymous type
select new
{
ID = e.ID,
LookUpID = a.ID
// some other data get populated here as well
};
Your code doesn't work at all. The part you think worked has never been executed. The first time you executed it was when you called Count.
As exception says you cannot construct mapped entity in projection. Projection can be made only to anonymous or non mapped types. Also it is not clear why you even need this. If your class is correctly mapped you should simply call:
var items = from e in db.Elements
where e.Something == something
select e;
If LookupID is mapped property of your Element class it will be filled. If it is not mapped property you will not be able to load it with single query to Element.