Reputation: 2463
I'm new to using Linq and just started a side project to learn some of the basics. I'm currently using Linq to Sql and all my DB Table relationships worked very well. Currently I have a Client table and a Project table. Each Client can have 1 or more Projects. Therefore, as you'd expect each Client object has a collection of Project objects after Linq does its magic.
I'm using the below code and it works well, but I think there is a better way of doing it. I need to pass my method a ProjectID and then select that Project from the Client:
private void PopulateStatusView(int projectID)
{
MyDataContext db = new MyDataContext();
var client = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"])
select u).SingleOrDefault();
if (client != null)
{
foreach (Project currentProject in client.Projects)
{
if (currentProject.id == projectID)
{
// Project Selected Here
statusProjectName.Text = currentProject.name;
}
}
}
else
{
// Session Expired
}
}
Can anyone let me know if there's a better solution rather than looping over each Project.
Thank you.
Upvotes: 0
Views: 739
Reputation: 422222
To get the client which has the specific project ID:
var client = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"]) &&
u.Projects.Any(x=>x.id == projectID)
select u).SingleOrDefault();
To get the project:
var project = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"]) &&
u.Projects.Any(x=>x.id == projectID)
select u.Projects.Where(x=>x.id == projectID).Single()).SingleOrDefault();
Upvotes: 2
Reputation: 592
You can replace the foreach look up with something like:
var project = client.Projects.Where(p=>p.id==projectID).SingleOrDefault();
if (project != null) statusProjectName.Text = project.name;
Upvotes: 1
Reputation: 351688
Try something like this:
clients.Projects.Where(
p => p.id == projectID
&& p.name == statusProjectName.Text);
Upvotes: 1