GridView doesn't show results with First() query extension - c#

I am using LINQ-to-Entities and have loaded up a Northwind Database (with LazyLoading=true).
var db = new NorthwindEntities();
var result = db.Orders.Where(x => x.CustomerID == "ANATR").First();
DataGridView1.DataSource = result;
The above code doesn't show up any items (one in this particular case) in the DataGridView. What am I doing wrong?
(If I remove the 'First()' it works fine and gives me several items)

The result is not a collection, that's why, you can not list it. First is a single object.

var db = new NorthwindEntities();
var result = db.Orders.Where(x => x.CustomerID == "ANATR").First();
DataGridView1.DataSource = result;
since result isn't a Collection this won't work you can use
var results =Enumerable.Repeat(result, 1);
To create single item in a list to do this or also
var results = new List<Order>() { result };
Will also work
And then bind to results instead of result

Your result is actually a single object not a collection of objects.
Try adding the result to an empty list.

Related

LINQ List overwrites previous value instead of setting new one

I have a LINQ query which outputs ToList it works fine other than the fact each time it's run it updates the original record instead of creating a new one.
On every run through this code the data.EventID changes so I'd like every record to appear in the list.
The code:
foreach(var data in vehicleqry)
{
bool inUK = boundryChecker.IsLongLatInUK((double)data.declatfloat, (double)data.declongfloat);
if (inUK == true)
{
var qryevent = (from e in db.events
where e.eventID == data.EventID
select new
{
e.eventID,
e.sysdatetime,
e.vehicleID
}).ToList();
}
{
I also have a list with the eventIDs in if I can use this to query the list?
I think what you actually want is to only run a single query instead of looping around. You can do this by making use of the Contains method:
var vehicleqry = ...;
// Get all of the individual event IDs for entries that are "inUK"
var vehicleEventIds = vehicleqry
.Where(ve => boundryChecker
.IsLongLatInUK((double)ve.declatfloat, (double)ve.declongfloat)
.Select(ve => ve.EventID);
// Get all the matching events
var qryevent = (from e in db.events
where vehicleEventIds.Contains(e.eventID)
select new
{
e.eventID,
e.sysdatetime,
e.vehicleID
}).ToList();

Adding list to a new list

Take if from the top. have a list that I return MyTableList.
var MyTableList = List<ExportDto>(List);
this tableList returns ID's that is needed to select another level from the same table.
IEnumerable<int?> rowselect = MyTableList.Where(n => n.ID != null)
.Select(n => n.ID);
this provides me with a list of ID's are then returned;
I use a
foreach (var item in rowselect)
getnewlist = getnewinfo.GetSinglerows(item.Value);
The main problem is for me Adding this new list and merging it with MyTableList.
Use List<T>.AddRange Method as following:
MyTableList.AddRange(getnewlist );

How to convert List<BsonDocument> to List<Class> in C#

Here what I am trying to do is to convert List of Bson Document to the list of Class. The main purpose of doing so is to filter the data from the list of Json data. I am using MongoDb for my database and C# for handling data. I have stored some data in MongoDb and trying to filter the data using FilterDefinition like this:
PROCESS 1
FileContext context = new FileContext();
var collection = context.Db.GetCollection<BsonDocument>("DBCollection");
var builder = Builders<BsonDocument>.Filter;
FilterDefinition<BsonDocument> Filter = builder.Eq("FileName", fileDetail.FileName) & builder.Eq("FileNumber", fileDetail.FileNumber.ToString());
var list = await collection.Find(Filter).ToListAsync();
In this way I am not been able to get the data in list. Therefore, I tried the other way like this:
PROCESS 2
FileContext context = new FileContext();
var collection = context.Db.GetCollection<BsonDocument>("DBCollection");
var list = await collection.Find(_ => true).ToListAsync();
List<MyClass> objList = null;
foreach (var item in objList)
{
objList = new List<MyClass>();
objList.Add(BsonSerializer.Deserialize<MyClass>(item));
}
if(objList.Count >0)
{
int count = objList.Where(x => x.FileName == "SOME_FILE_NAME" && x.FileNumber == 1).Count();
}
This way I am able to get the data and able to filter data as well but I know this is not good programming at all as this will have lots of waiting time if the size of data increases in future.
Here my questions are:
What is wrong in PROCESS 1?
How to Convert List<BsonDocument> to List<MyClass>?
How to filter List<BsonDocument>?
var collection = context.Db.GetCollection<BsonDocument>("DBCollection");
should be:
var collection = context.Db.GetCollection<MyClass>("DBCollection");
That way you should be able to use the Find method to check your FileName and FileNumber using something like:
var objList = await collection.Find(x => x.FileName == "FILENAMEHERE" && x.FileNumber == 1).ToListAsync();

Linq replace column value with another value

Well, im doing a linq query to get a list of results with the same column, and then i need to replace that column value with a new one.
First Code:
var db = GetContext();
var result = from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f;
foreach (var item in result)
{
var projectStateHistoryUpdate = db.ProjectStateHistories.Find(item.Id);
projectStateHistoryUpdate.ProjectId = newProjectId;
db.Entry(projectStateHistoryUpdate).State = EntityState.Modified;
}
db.SaveChanges();
I searched for some answers, and i found that i can use Select, and make a new object (Linq replace null/empty value with another value)
Second Code:
var result = (from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { Id = d.Id, EventName = d.EventName, LogUser = d.LogUser, ProjectId = newProjectId, TimeStamp = d.TimeStamp });
And even, Third Code:
var db = GetContext();
var result = (from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { ProjectId = newProjectId});
But only the First Code works.
I wanted to ask what i am doing wrong, since i think it is better to change the value with a query, instead of using a foreach.
See code below:
var db = GetContext();
(from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f)
.ToList()
.ForEach(i => i.ProjectId = newProjectId);
db.SaveChanges();
Alternatively:
var db = GetContext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
The shortest way I know of to replace your code is this:
var db = getcontext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
Other answers can be found here
I've just had a thought that could help you, I am just free coding here!
If you just put the for each as part of the select, and then save your changes will that work?
foreach (var source in db.ProjectStateHistories.Where(x => x.ProjectId == oldProjectId))
{
source.ProjectId= newProjectId;
db.Entry(source).State = EntityState.Modified;
}
db.SaveChanges();
I think this is a more efficient way of doing it.
Also the .Select() method is only really useful if you need to Project to a view Model, it won't change the variables in the database, just show them in the newly declared object.
Thanks,
Phill

Linq query change from List<string> to List<T> where clause

I have a linq query that works when it I had a list of a single value now that I change to having a List that has several properties I need to change the where clause
So this works:
List<string> etchList = new List<string>();
etchList.Add("24");
var etchVect = (from vio in AddPlas
where etchList.Any(v => vio.Key.Formatted.Equals(v))
let firstOrDefault = vio.Shapes.FirstOrDefault()
where firstOrDefault != null
select new
{
EtchVectors = firstOrDefault.Formatted
}).ToList();
However I have a new hard coded list (which will represent incoming data:
List<ExcelViolations> excelViolations = new List<ExcelViolations>();
excelViolations.Add(new ExcelViolations
{
VioID = 24,
RuleType = "SPACING",
VioType = "Line-Line",
XCoordinate = 6132,
YCoordinate = 10031.46
});
So the NEW Linq query looks like this, but is obviously will not work as
AddPlas is a List and so using this other list of excelviolations, I wish to have it do where on each one of the properties in the excelviolations list
var etchVect = (from vio in AddPlas
where excelViolations.Any(vioId => vio.Key.Formatted.Equals(vioId))
let firstOrDefault = vio.Shapes.FirstOrDefault()
select new
{
EtchVectors = firstOrDefault.Formatted
}).ToList();
Now, since this is a list within a list, I would like to do something like add in each of the properties
so for example:
where excelViolations.VioID.Any(vioId => vio.Key.Formatted.Equals(vioId))
However that is not possible, but you see that I'm trying to access the property of VioID that is in the excelViolations and match it to the Key which is in vio list
Just change this line
where excelViolations.Any(vioId => vio.Key.Formatted.Equals(vioId))
to
where excelViolations.Any(excelVio => vio.Key.Formatted.Equals(excelVio.VioID))
then i thought it will works

Categories