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 thanFirstOrDefault().Why is this an issue:
First()will throw an exception if there is no address for the given client id.FirstOrDefault()will returnnullif 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: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.