简体   繁体   English

C#-EF储存库

[英]C# - EF Repository

I've made up 2 possible ways for how my EF implementation should interact with my app. 我已经提出了两种可能的方式来实现我的EF实现与我的应用程序进行交互。 The first one is a simple Repository, and the second is a rather dynamic version. 第一个是一个简单的存储库,第二个是一个相当动态的版本。 Both of those solutions produce the same sql queries according to the sql profiler - so nothing more, nothing less. 这两种解决方案都根据sql探查器生成相同的sql查询-因此,仅此而已。

Now is my question, is there any perfomance overhead for solution 1 compared to solution 2? 现在是我的问题,与解决方案2相比,解决方案1是否有性能开销? - and if yes, does it matter in the long run? -是的话,从长远来看,这有关系吗?

Solution 1: 解决方案1:

public class Repository
{
    public MyContext Ctx = new MyContext();

    public IEnumerable<T> GetAll<T>() where T : class
    {
        return Ctx.Set<T>();
    }
}

... And the code that calls it: ...和调用它的代码:

var rep = new Repository();

Console.WriteLine("DEALERS:");
foreach(var dealer in rep.GetAll<Dealer>())
{
    Console.WriteLine(dealer.Name);
}

Console.WriteLine("CARS:");
foreach (var car in rep.GetAll<Car>())
{
    Console.WriteLine(car.CarName);
}

Solution 2: 解决方案2:

public class Repository<T> where T : class
{
    private readonly MyContext _ctx = new MyContext();
    private readonly IDbSet<T> _dbset;

    public Repository()
    {
        _dbset = _ctx.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {
        return _dbset;
    }
}

... And the code that calls it: ...和调用它的代码:

var dealerRep = new Repository<Dealer>();
var carRep = new Repository<Car>();

Console.WriteLine("DEALERS:");
foreach(var dealer in dealerRep.GetAll())
{
    Console.WriteLine(dealer.Name);
}

Console.WriteLine("CARS:");
foreach (var car in carRep.GetAll())
{
    Console.WriteLine(car.CarName);
}

EF是一个ORM,并且已经实现了Repository模式,绝对不需要将其包装在您自己的存储库中。

You need to access the same set at least twice in each repository, to see if the two solutions really act the same. 您需要在每个存储库中至少访问两次相同的集合,以查看两个解决方案是否确实发挥作用。

Check profiler on 2nd call and perhaps make changes to data via another context, between accesses, to make sure behavior is the same. 在第二次调用时检查事件探查器,并可能在访问之间通过另一个上下文对数据进行更改,以确保行为相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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