Oskar Kjellin
Oskar Kjellin

Reputation: 21860

Linq To Sql One To Many

Say I have 3 tables, Cars, Persons, CarOwners.

Cars is just a table of cars and Persons are different people that can own cars. CarOwners has a CarId and a PersonId relationship and a CarOwnerId PK.

If I just create the relationship and then drag them to the linq context, a property of the Person class will be generated called CarOwners. To get the cars that this person owns I would have to do the following query:

var cars = person.CarOwners.Select(c=> c.Car);

But I would like to be able to do:

var cars = person.Cars;

Is that at all possible? The extra step is quite annoying.

Upvotes: 1

Views: 859

Answers (2)

Kamyar
Kamyar

Reputation: 18797

Try to remove the CarOwnerId from CarOwners in your sql database. Then select CarId and PersonId in designer mode in SSMS (using shift key), right click and select `Set Primary Key.

In EF 4, you'll get only navigation keys in your model this way (you can use: Person.Cars and Car.Persons). Not sure about L2S.

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

You can just create a new property on Person:

public partial class Person
{
    public IEnumerable<Car> Cars
    {
        get { return this.CarOwners.Select(c => c.Car); }
    }
}

Or upgrade to Entity Framework where you can separate logical model from physical model.

Upvotes: 4

Related Questions