GridView Only populating 1 result - c#

I'm currently working to add Data to a GridView. The data comes from 2 tables that are on different databases. Currently I am able to populate the first entry, but it does not populate past that. here is the code:
void FillOrder(int inv)
{
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
foreach (var order in qryOrder)
{
int prodID = order.ProductID;
int itemCount = qryOrder.Count;
var qryProducts = (from p in _pro.Products
where p.ProductID == prodID
select new
{
p.ProductID,
p.ProductName
}).ToList();
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals prodID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();
}
}
Can anyone help as to why it's only populating the first entry?

If the number of products involved is relatively small, (and since this query seems to be relate to one invoice, I would think that is true), then you can probably use something like the code below.
This is removing the loop, but the contains method will probably generate a SQL statement something like select ProductID, ProductName from products where productID in (,,,,,,) so may fail if the number of parameters is extremely large.
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
// Get the productIDs
var productIDS = qryOrder.Select(o=>o.ProductID).Distinct().ToList();
// Get the details of the products used.
var qryProducts = (from p in _pro.Products
where productIDS.Contains(p.ProductID)
select new
{
p.ProductID,
p.ProductName
}).ToList();
// Combine the two in memory lists
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals s.ProductID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();

Related

how to apply join or innerquery to connect two table

Here MyChildTable contains only id and the parent table contains id + name.
I have written a query to fetch the existing data from the table
await _dbContext.MyChildTable
.Where(c => c.CustomerId == **(select customerid from tableParent where customername= reqcustomername)**
Here i want to match customerId with the matching customer id from the second table ie tableParent.How to replace the query in to linq to get the proper record.select customerid from tableParent where customername= reqcustomername i want to replace this selection
I don't understand what you mean
so my maybe answer error
LINQ
using (entity entityData = new entity())
{
var checkqry2 = from T1 in entityData.MyChildTable.AsNoTracking()
join T2 in entityData.tableParent on
T1.CustomerId equals T2.customerid
where T1.customerid == "ID" && T2.customername == reqcustomername
group new { T2.customerid, T2.customername } by new { T1.customerid, T1.customername } into c
orderby c.Key.customerid
select new { customername=c.Key.customername,
customerid=c.Key.customerid,
};
}
you can try entity lambda
entity lambda
using (entity entityData = new entity())
{
var query1 = entityData.MyChildTable
.Join(entityData.tableParent , o => o.CustomerId , p => p.CustomerId , (o, p) => new
{
o.CustomerId,
p.customername,
}).Where(o => o.CustomerId == "123" && o.customername == "name").ToList();
}
Here I want to match customerId with the matching customer id from the
second table ie tableParent.How to replace the query in to linq to get
the proper record.select customerid from tableParent where
customername= reqcustomername i want to replace this selection
Well, lot of way around to handle this kind of scenario. Most easy and convenient way you could consider by using linq join or linq Enumerable which you can implement as following:
Sample Data:
var childList = new List<ChildTable>()
{
new ChildTable(){ Id =101,ChildName = "Child-A",CustomerId = 202},
new ChildTable(){ Id =102,ChildName = "Child-B",CustomerId = 203},
new ChildTable(){ Id =103,ChildName = "Child-C",CustomerId = 202},
new ChildTable(){ Id =104,ChildName = "Child-D",CustomerId = 204},
};
var parentList = new List<ParentTable>()
{
new ParentTable(){ Id =301,ParentName = "Parent-A",CustomerId = 202},
new ParentTable(){ Id =302,ParentName = "Parent-B",CustomerId = 202},
new ParentTable(){ Id =303,ParentName = "Parent-C",CustomerId = 203},
new ParentTable(){ Id =304,ParentName = "Parent-D",CustomerId = 205},
};
Linq Query:
Way One:
var findMatchedByCustId = from child in childList
where (from parent in parentList select parent.CustomerId)
.Contains(child.CustomerId)
select child;
Way Two:
var usingLinqJoin = (from parent in parentList
join child in childList on parent.CustomerId equals child.CustomerId
select parent).ToList().Distinct();
Output:
Note: If you need more information you could check our official document for Linq join and Linq Projction here.

Linq Query to get latest of eact defect ID

In al_jira_defect_out table i have Batch_Insert_Timestamp, AL_Defect_ID columns along with other columns.And In this table there will be duplicate AL_Defect_IDs with different Batch_Insert_Timestamp.
As per below code in linq i am getting all records which are Jira_Status == 0
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
select new Issue
{
fields = new CreateIssue
{
project = new Project
{
key = g.jira_project_key
},
issuetype = new Issuetype()
{
name = t.jira_equivalent
},
description = d.Defect_ShortDesc,
summary = d.Defect_DetailDesc,
versions = new List<Versions>
{
new Versions {name = d.Defect_Release_DetectedIn}
},
priority = new Priority
{
name = d.Defect_Severity_Name
},
customfield_10182 = d.AL_Defect_ID.ToString(),
}
}).Select().ToList();
i am getting record with AL_Defect_IDs duplicate.
But i required latest records[Max(d.Batch_Insert_Timestamp)] of each d.AL_Defect_ID with all required columns
can any one please help me to get linq query
If you group on AL_Defect_IDs, you can order by Batch_Insert_Timestamp and take the last (latest) one:
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
group new { d, p, t } on d.AL_Defect_ID into dptg
let dpt = (from dpt in dptg order by dpt.d.Batch_Insert_Timestamp select dpt).Last()
select new // ... whatever using dpt
Your sample code doesn't use p in the select, so you could leave it out of the grouping.

Creating table which changes a column in order to remove repeated values in rows

Sorry if the title was confusing.
Currently I am practicing with Entity Framework and LINQ expressions and got stuck on this.
I have a table with columns:"Personal ID", "Name", "Surname", "Phone ID" and all values on Phone ID are unique. I would like to create another table in which there would be same columns except for last being "Phone Count" which shows how many phones are associated with same Person(Personal ID). I want the table to show only 3 first highest count rows.
Here is the code i've wrote to make table that i've described above.
using (var db = new PRDatabaseEntities())
{
var query = from a in db.Person
join t in db.Repairs on a.PID equals t.Repairman_PID
orderby a.PID
select new
{
a.PID,
a.Name,
a.Surname,
t.Phone_ID
};
}
You could try with following group by LINQ query:
// First, generate a linq query
var query = from a in Persons
join t in Repairs on a.PID equals t.Repairman_PID
group new { a, t } by new { a.PID, a.Name, a.Surname } into g
select new
{
PID = g.Key.PID,
Name = g.Key.Name,
Surname = g.Key.Surname,
PhoneCount = g.Count()
};
// Then order by PhoneCount descending and take top 3 items
var list = query.OrderByDescending(t => t.PhoneCount).Take(3).ToList();
Try this:
using (var db = new PRDatabaseEntities())
{
var query = db.Person
.GroupJoin(db.Repairs,
p => p.PID, r => r.PID,
(p, r) => new {
PID = p.PID,
Name = p.Name,
Surname = p.Surname,
Count = r.Count()
};
}

Grouping by ID and displaying the top 1 with Linq

Looking for a bit of advice on grouping with entity framework and linq.
So i have a table "tbl_ChatLog" that contains userID and sendToUserID etc...and with this data i'm trying to display the "Top 1" from each "SendToUserID"
So in my UI it would look like so:
1001 (Contains multiple but show the top 1)
1003 (Contains multiple but show the top 1)
1008 (Contains multiple but show the top 1)
1009 (Contains multiple but show the top 1)
The start of my code below:
public static List<Chat> getChatMessage()
{
var entities = new FreeEntities();
//My ID
Business.User user = Business.User.getUserBySecurityToken();
List<Chat> chatMessages =
(
from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
select new Chat
{
uid = (int)cm.UserID,
sendToUserID = (int)cm.SendToUserID,
message = cm.Message, dateAdded = (DateTime)cm.DateAdded
}
).OrderByDescending(x => x.dateAdded).ToList();
return chatMessages;
}
Hoping you can help me out on this one. Grouping always seems to throw me.
Much appreciated,
Terry
You could use groupby:
List<Chat> chatMessages =
(from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
orderby cm.DateAdded descending
group cm by cm.sendToUserID into grp
select new Chat
{
uid = grp.FirstOrDefault().UserID,
sendToUserID = grp.Key,
message = grp.FirstOrDefault().Message,
dateAdded = grp.FirstOrDefault().DateAdded
}).ToList()
This will get you a list of your table data grouped by sendToUserID and the first entry of each group containing every property including sendToUserID.
The original problem was trying to select the first message from each unique "SendToUserId" and grouping by UserId and then selecting into a DTO was a nightmare but i managed to get a simple work around. Code below:
getFirstChatMessage()
{
var entities = new FreeEntities();
//User ID
Business.User user = Business.User.getUserBySecurityToken();
// Create new list of Chat
List<Chat> chatList = new List<Chat>();
var res = from c in entities.tbl_ChatLog
where c.UserID == user.uid
group c by c.UserID
into groups
select groups.OrderByDescending(p => p.DateAdded).FirstOrDefault();
foreach (var r in res)
{
chatList.Add(new Chat()
{
uid = (int)r.UserID,
sendToUserID = (int)r.SendToUserID,
message = (from m in entities.tbl_ChatLog where m.UserID == (int)r.SendToUserID
orderby r.DateAdded descending select m.Message).FirstOrDefault(),
dateAdded = (DateTime)r.DateAdded,
fullName = (from b in entities.tbl_Bio where b.UserID == (int)r.SendToUserID
select b.FirstName + " " + b.SurName).FirstOrDefault()
});
}
return chatList;
}

C# LINQ: Get count for each row

Here the query for retrieving all the comptes in my base.
I would like to add a number within the object GridCompte in order to count the element inside the list (1,2,3...):
var comptes = (from c in Comptes
join s in Societies on c.IdSoc equals s.IdSoc
select new GridCompte
{
SocCompteId = c.IdCompte,
Name = c.Name,
Nb = ??? COUNT ???,
.....
SocName = s.Name
}).ToList();
I tried using the group statement, but i didn't manage to achieve my goal.
Any suggestions?
First prepare your linq only for the fields you want to get
var comptes = from c in Comptes
join s in Societies on c.IdSoc equals s.IdSoc
select new
{
SocCompteId = c.IdCompte,
Name = c.Name,
.....
SocName = s.Name
};
Now use index option that is available in Select
var finalComptes = (comptes.AsEnumerable()
.Select((comptes, index) => new GridCompte()
{
SocCompteId = c.IdCompte,
Name = c.Name,
Nb = index + 1,
.....
SocName = s.Name
}).ToList();

Categories

Resources