开发者

Linq To Sql One To Many

开发者 https://www.devze.com 2023-03-25 17:51 出处:网络
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.

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 r开发者_开发问答elationship 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消