简体   繁体   中英

Avoid include duplication in EF

I have two methods with same include part(these methods only for describe problem)

    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);
    }

How can these three includes make common to avoid code duplication.

Develop a method like :

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>();
}

Note : I've no knowledge about executeQuery method, But I think my code will works, juts to be sure after that use Entity Framework profiler or SQL profiler to be sure everything is ok

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM