在ToList()上关系的LINQ-2-SQL扩展

时间:2012-03-04 19:02:47

标签: linq linq-to-sql

我有一个DataLayer类(LINQ2SQL,而不是实体框架),它从数据库返回行,如下所示:

    public ReadOnlyCollection<UserCars> Cars
    {
        get
        {
            using (var context = new TransportopiaDataContext())
            {
                var result = (from car in context.UserCars
                              where car.UserId == UserId
                              select car);
                return result.ToList().AsReadOnly();
            }
        }
    }

现在,正如您所知,您必须执行ToList(),因为当您离开using()子句时,datacontext超出范围。问题是存在外键关系;虽然上下文仍在范围内,但您可以这样做:

string foo = car.Manufacturer.Name;

但是在处理完上下文后执行此操作会导致错误。所以我的问题是:

“有没有办法做ToList(),这样外键关系也会被扩展?”

1 个答案:

答案 0 :(得分:3)

您可以在执行查询前在DataLoadOptions中指定:

using (var context = new TransportopiaDataContext())
{
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<UserCar>(x => x.Manufacturer);
    context.LoadOptions = options;
    var result = (from car in context.UserCars
                    where car.UserId == UserId
                    select car);
    return result.ToList().AsReadOnly();
}