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?

3
  • 1
    3.) if you're programming a web application, you can always use a method One Context Per Request, as I've shown here stackoverflow.com/a/10153406/1289283 Commented Mar 24, 2014 at 14:29
  • @walther what about other than web applications? Commented Mar 24, 2014 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 ;) Commented Mar 24, 2014 at 19:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.