简体   繁体   中英

Linq to Sql - Select from 1:Many

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.

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();

Try something like this:

clients.Projects.Where(
    p => p.id == projectID 
    && p.name == statusProjectName.Text);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM