C# 我应该在哪里连接到上下文以获得更好的性能?

C# 我应该在哪里连接到上下文以获得更好的性能?,c#,performance,entity-framework,C#,Performance,Entity Framework,我想使用EF并了解两种使用上下文访问某类方法数据的方法: 1.每类方法的传递连接: public partial class MyEntity { public static int Add(MyEntityConnection context,MyEntity input) { context.MyEntity.AddObject(input); context.SaveChanges(); return input.Id;

我想使用EF并了解两种使用上下文访问某类方法数据的方法:

1.每类方法的传递连接:

 public partial class MyEntity
 {
    public static int Add(MyEntityConnection context,MyEntity input)
    {
        context.MyEntity.AddObject(input);
        context.SaveChanges();
        return input.Id;
    }
 }
2.在每个方法上独立使用上下文:

 public partial class MyEntity
 {
    public static int Add(MyEntity input)
    {
        using (var context = new MyEntityConnection())
        {
            context.MyEntity.AddObject(input);
            context.SaveChanges();
            return input.Id;
        }
    }
 }

以上哪种方法或其他方法更好?

根据walther的评论,我建议每个请求使用上下文,但使用依赖项注入和存储库模式来管理生命周期

比如:


3。)如果你在编写一个web应用程序,你总是可以使用一个方法
每个请求一个上下文
,正如我在这里所展示的@walther,除了web应用程序之外,还有什么呢?这主要取决于你的体系结构,你想如何布局你的应用程序,你习惯了什么,什么最适合你。。。恐怕有太多的模式,不能指出一个是“最佳解决方案”。它因程序员而异。只要确保你坚持一种编程风格。这是最重要的部分;)