我正在與具有性能問題的SQL Server上的實體框架的項目ASP.NET MVC3。實體框架 - 查詢執行性能問題
每次使用EF和Linq從視圖/表中加載數據。我可以通過SQL Server Profiler看到所有的表/視圖內容都被檢索到,因爲where條件不會出現在profiler中。我認爲只有後來被LINQ過濾了。
它是正確的嗎?如何只加載我首先需要在SQL Server上的數據?
這是我的示例代碼:
var query = unitWork.City.GetFirstorDefault(item => item.City == cityCode);
下面我們數據層與數據呼叫例如提取。感謝您的答覆。
public class UnitOfWork : IUnitOfWork, IDisposable
{
#region CONSTRUCTOR
public UnitOfWork()
{
_context = new MyApplicationEntities(); //DataContext
_context.ContextOptions.LazyLoadingEnabled = true;
_context.ContextOptions.UseLegacyPreserveChangesBehavior = false;
}
#endregion
// DESC_RECHARGEABLE is a table in DB
public IGenericRepository<DESC_RECHARGEABLE> RepRechargeable
{
get{return _repRechargeable ?? (_repRechargeable = new GenericRepository<DESC_RECHARGEABLE>(_context));}
}
}
public interface IGenericRepository<T> : ICollection<T>
where T : class
{
IEnumerable<T> Query(Func<T, bool> predicate);
void Update(T entity);
T GetFirstorDefault(Func<T, bool> predicate);
IEnumerable<T> GetAll();
T GetByKey(Func<T, bool> predicate);
bool Remove(T entity);
void Add(T entity);
ObjectSet<T> GetQuery();
}
public class GenericRepository<T> : IGenericRepository<T>
where T : class
{
private MyApplicationEntities Currentcontext;
public ObjectSet<T> entitySet;
private List<GenericRepository<T>> _list = null;
private string entityName;
public GenericRepository(MyApplicationEntities context)
{
if (context == null)
throw new ArgumentNullException("context");
this.Currentcontext = context;
this.entitySet = context.CreateObjectSet<T>();
this.entityName = entitySet.Name;
}
#region READ
public IEnumerable<T> Query(Func<T, bool> predicate)
{
return this.entitySet.Where(predicate);
}
public T GetFirstorDefault(Func<T, bool> predicate)
{
return this.Query(predicate).FirstOrDefault();
}
public IEnumerable<T> GetAll()
{
return this.entitySet.AsEnumerable();
}
public T GetByKey(Func<T, bool> predicate)
{
return this.Query(predicate).FirstOrDefault();
}
#endregion
}
//這裏客戶端調用示例,加載所有DESC_RECHARGEABLE行的條件
var tempList = _unitofWork.RepRechargeable.Query(item => item.COMPANY_CODE == companyCode
&& item.DIVISION_CODE == divisionCode && !string.IsNullOrEmpty(item.PROPERTY));
你應該告訴我們你的Linq代碼 –
告訴我們代碼 –
顯示'unitWork.City'和'GetFirstorDefault'方法的執行情況 – Moho