3

I want to use EF and know two way to use context for accessing data for methods of some class:

1.passing connection for each method of class:

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

2.using context on each method independently:

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

which of above or other ways to do it is better?

Majid
  • 13,853
  • 15
  • 77
  • 113
  • 1
    3.) if you're programming a web application, you can always use a method `One Context Per Request`, as I've shown here http://stackoverflow.com/a/10153406/1289283 – walther Mar 24 '14 at 14:29
  • @walther what about other than web applications? – Majid Mar 24 '14 at 14:36
  • That mostly depends on your architecture, how do you want to layout your application, what are you used to, what suits you the best... I'm afraid there are too many patterns out there to point one out as "the best solution". It varies from programmer to programmer. Just make sure you stick to one programming style. That's the most important part ;) – walther Mar 24 '14 at 19:15

1 Answers1

1

I'd recommend context per request as per walther's comment, but use Dependency injection and repository pattern to manage the lifetime.

Something like:

How-to inject the Entity Framework DbContext into the ConfigurationBasedRepository of SharpRepository

Community
  • 1
  • 1
Kaido
  • 3,383
  • 24
  • 34