1

我有两种方法具有相同的包含部分(这些方法仅用于描述问题)

    public Car GetCarByChildEntityId(long id)
    {
        var query = DataContext.AsQueryableFor<RTraining>()
            .Where(rb => rb.Id == id)
            .Include(rb => rb.Car.CarStatus)
            .Include(rb => rb.Car.item.Customer)
            .Include(rb => rb.Car.item.MyItem.Wheel.Customer);

        return executeQuery(query).SingleOrDefault().Car;

    }


    public IEnumerable<IEntity> GetEntities()
    {
        var query = DataContext.AsQueryableFor<RTraining>()
            .Include(rb => rb.Car.CarStatus)
            .Include(rb => rb.Car.Item.Customer)
            .Include(rb => rb.Car.Item.MyItem.Wheel.Customer);

        return executeQuery(query);
    }

这三个包括如何使通用以避免代码重复。

4

1 回答 1

3

开发一个方法,如:

private IQueryable<Car> getCommonQuery()
{
            DataContext.AsQueryableFor<RTraining>()
            .Include(rb => rb.Car.CarStatus)
            .Include(rb => rb.Car.Item.Customer)
            .Include(rb => rb.Car.Item.MyItem.Wheel.Customer);
}

public Car GetCarByChildEntityId(long id)
{
     return executeQuery(getCommonQuery()).SingleOrDefault(rb => rb.Id == id).Car;
}

public IEnumerable<IEntity> GetEntities()
{
     return executeQuery(getCommonQuery()).OfType<IEntity>();
}

注意:我对 executeQuery 方法一无所知,但我认为我的代码会起作用,只是为了确保之后使用实体框架分析器或 SQL 分析器来确保一切正常

祝你好运

于 2013-09-02T14:59:10.717 回答