繁体   English   中英

存储库模式以从dbset.local或数据库获取数据

[英]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.

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