Linq包含子对象属性

时间:2015-01-06 10:04:36

标签: c# linq include

listsItem可以是设备和车辆的父对象。我希望根据子类的类型包含子类的属性。

var type = GetAllQuery(context).FirstOrDefault(x => x.Id == id);

var listedItem = GetAllQuery(context)
                        .Include(x => x.Images)
                        .Include(x => x.User);

if (type.GetType().BaseType == typeof(Vehicle))
                    {

var vehicle = listedItem as IQueryable<Vehicle>;
                        return vehicle.Include(x => x.VehicleBrand).Include(x => x.VehicleModel).FirstOrDefault(x => x.Id == id);
}

设备相同。由于某种原因车辆返回null,我似乎无法找出原因。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

包含在EF返回ObjectQuery<T>中,您不应将其转换为Queryable。使用as ObjectQuery<Vehicle>。但你不需要实际转换,它已经是车型

同时清理代码,如果使用开关更换,最好建议使用工厂。

像这样的东西

public class IncludeConfiguratorFactory
    {
        public static IConfigurator Get<T>(T type)
        {
            switch (type.Name)
            {
                case "Vehicle":
                    return new VehicleConfigurator();
            }
        }
    }

    public class VehicleConfigurator : IConfigurator
    {

        #region IConfigurator Members

        public void Configure<T>(ObjectQuery<T> items ) where T : Vehicle
        {
            var vehicle = items.Include(x => x.VehicleBrand);
            vehicle = items.Include(x => x.VehicleModel);
        }

        #endregion
    }
    public interface IConfigurator
    {
        void Configure<T>(ObjectQuery<T> items);
    }

并致电

var listedItem = GetAllQuery(context).Include(x=>x.Images).Include(x => x.User);

        var provider = IncludeConfiguratorFactory.Get(itemType);
        provider.Configure(listedItem);

请注意:以上代码未经过测试,可能包含语法错误