简体   繁体   中英

Many to many in LINQ to SQL

In my database I have a customer, who can have multiple locations and a location can have multiple customers. I have dragged my database design into a Linq To SQL dataclasses file and this is how it currently looks.

数据库

In my form I am trying to retrieve the adress (or multiple) from a customer. I have tried the following code but I always get the same error: Sequence contains no elements, while it does have elements! (Customer with ID 2, Location with ID 1 and the join table with 2,1)

    public static locatie getLocationByCustomer(int id)
    {
       var query = (from v in dc.locaties
                      from e in v.locatie_klants
                      where e.klant_id == id
                      select v);


        locatie locatie = query.First();
        return locatie;
    }

Translations: klant --> Customer || locatie --> Location || locatie_klant --> location_customer

I'm not sure what I'm doing wrong here. I'm also wondering how I would save a new customer to the database (with multiple locations), any ideas?

Thanks for the help!

Apparently the customer your querying is not related to any location. Therefore your query does not return any elements. This itself is not an issue, but in your sample you are using First() rather than FirstOrDefault() .

Why is this an issue:

  • First() will throw an exception if there is no address for the given client id.
  • FirstOrDefault() will return null if there is no address for the given client id.

Especially with relations like these you should stick to FirstOrDefault() since you can never be sure that there is a relation present for the items you are querying.

Here is a sample on how to add a Customer + CustomerLocations :

var newCustomer = new klant()
{
    // set neccessary properties
};

var newCustomerLocation1 = new locatie_klant()
{
    // set neccessary properties
};

var newCustomerLocation2 = new locatie_klant()
{
    // set neccessary properties
};

using (var context = new DBContext())
{
    context.klants.Add(newCustomer);
    context.locatie_klants.Add(newCustomerLocation1);
    context.locatie_klants.Add(newCustomerLocation2);
    context.SaveChanges():
}

Some general advice:
Stick to English names for development objects. This is considered best practice also makes your life easier when using questions on so / forums.

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