[英]Repository pattern to get data from dbset.local or database
我正在編寫一個方法,該方法將遍歷一些數據並在數據庫中創建記錄,該方法利用了存儲庫。
最初是這樣的:
///Lets assume that there is a string array called arr somewhere above this.
var repo = new ItemRepository();
for (int i = 0; i<1000; i++)
{
if (repo.MyItems.Count(x=>x.ID == arr[i]) == 0)
{
//Doesn't Exist Create
repo.MyItems.Add(new Item(arr[i]));
repo.Save();
}
else
{
//Here I will get an instance of the entity that already exists and do some updates to it
}
}
可行,但是因為每次迭代都將其保存到數據庫中,所以速度很慢,所以我要做的就是將其更改為以下形式:
var repo = new ItemRepository();
for (int i = 0; i<1000; i++)
{
if (repo.MyItems.Count(x=>x.ID == arr[i]) == 0)
{
//Doesn't Exist Create
repo.MyItems.Add(new Item(arr[i]));
}
else
{
//Here I will get an instance of the entity that already exists and do some updates to it
}
}
repo.Save();
因此只有在創建所有實體之后才進行保存,因此它是一個大的數據庫插入而不是數千個。
問題在於,因為項目尚未持久化到我的數據庫中,所以repo.MyItems.Count(x => x.ID == i)不會帶回任何東西(盡管實體已添加到dbset.Local采集。
我想我的問題是我該如何修改我的存儲庫以允許我查詢本地集合和數據庫-因為那很重要,它們可能存在於數據庫中,或者它們可能已經添加到存儲庫中但沒有插入數據庫中。
上面是偽代碼,但是有點代表我在做什么,repository方法有點像
public int count(string val)
{
IQueryable<T> data = _dbSet;
return data.Count(x=>x.COLUMNNAME == val);
}
再次,這只是我在回購中所擁有的東西的代表,但是它應該可以讓我對我要去的事情有所了解。
如果有人感興趣,這就是我實現的方法,並且似乎可行,但是我最終放棄了它,因為意識到這將幾乎允許“臟讀”數據,從而對其余數據產生影響系統的性能,因此我們認為,多次保存對性能的影響要比對系統的大部分進行重新處理更為可取-或實施允許臟讀取的回購...
請注意,GetSingle取代了我在上面的偽代碼中擁有的Count。
public T GetSingle(System.Linq.Expressions.Expression<Func<T, bool>> filter = null)
{
//Check the local collection first
IQueryable<T> localEntities = _dbset.Local.AsQueryable();
if (filter != null)
{
localEntities = localEntities.Where(filter);
}
if (localEntities.Count() > 0)
{
return localEntities.FirstOrDefault();
}
else
{
//A local version of this was not found - try the database.
IQueryable<T> query = this._dbset;
if (filter != null)
{
query = query.Where(filter);
}
return query.FirstOrDefault();
}
}
如果有更好的方法,我真的很想知道,因為這是我可能會再次遇到的問題,下次我可能需要繼續解決它!
我希望我正確理解了這個問題,這是我通常要做的:
var repo = new ItemRepository();
Int32 index = 0;
Int32 localIndex = 0;
while (index < arr.Length) {
repo.MyItems.Add(new Item(arr[index]));
index++;
localIndex++;
if (localIndex == 1000) {
repo.Save();
localIndex = 0;
}
}
if (localIndex > 0) {
repo.Save();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.