当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Entity Framework + 'using' pattern best practice

问题描述:

I'm wondering what would be best practice in this scenario:

I have method which calls some other method in using statement (disposable Database Context), and that other method also needs to access Database Context, so this is option 1:

using (var db = new Database())

{

// some code here

//calling other function

var cnt = SomeFunction();

}

int SomeFunction()

{

using (var db = new Database())

{

// some code here for example:

return db.Users.Count();

}

}

And here is option 2:

using (var db = new Database())

{

// some code here

//calling other function

var cnt = SomeFunction(db);

}

int SomeFunction(Database db)

{

return db.Users.Count();

}

Note: Database looks smth. like this:

 public class Database : IdentityDbContext<User>

{

public Database()

: base("DefaultConnection", throwIfV1Schema: false)

{

Configuration.LazyLoadingEnabled = true;

}

public DbSet<IdentityUser> AspNetUsers { get; set; }

}

I would go with option 2, because there is no need for initialization of Database Context again, but I'm not sure if this is correct way of doing this.

网友答案:

DbContext instances have their own changetracker. In case you want to use a changed DbSet inside SomeFunction, use the same DbContext. If not, you can choose whatever you prefer.

网友答案:

I would go with option 3: overload your SomeFunction.

int SomeFunction()
{
  using (var db = new Database())
    return SomeFunction(db);
}

int SomeFunction(Database db)
{
  return db.Users.Count();
}

Let the caller decide whether to pass in an existing Database. Sometimes it makes sense, if the caller has one already, as in your example. Other times, the caller just has one database operation to perform, and then there is some benefit in simplifying the API by not bothering the caller with the responsibility of creating a Database and remembering to dispose of it properly.

分享给朋友:
您可能感兴趣的文章:
随机阅读: