我有两个方法,包括相同的部分(这些方法仅用于描述问题)
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);
}
这三个包括如何共同避免代码重复。
答案 0 :(得分: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方法一无所知,但我认为我的代码可以正常运行,确保在使用Entity Framework Profiler或SQL profiler之后确保一切正常
祝你好运