我想知道在这种情况下最佳做法是什么:
我有使用语句(一次性数据库上下文)调用其他方法的方法,而其他方法也需要访问数据库上下文,所以这是选项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();
}
}
这是选项2:
using (var db = new Database())
{
// some code here
//calling other function
var cnt = SomeFunction(db);
}
int SomeFunction(Database db)
{
return db.Users.Count();
}
注意:Database
看起来很糟糕。像这样:
public class Database : IdentityDbContext<User>
{
public Database()
: base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<IdentityUser> AspNetUsers { get; set; }
}
我会使用选项2,因为不需要再次初始化Database Context,但我不确定这是否是正确的方法。
答案 0 :(得分:2)
DbContext
个实例有自己的更改跟踪器。如果您想在DbSet
内使用已更改 SomeFunction
,请使用相同的DbContext
。如果没有,你可以选择你喜欢的任何东西。
答案 1 :(得分:1)
我会选择选项3:重载SomeFunction
。
int SomeFunction()
{
using (var db = new Database())
return SomeFunction(db);
}
int SomeFunction(Database db)
{
return db.Users.Count();
}
让来电者决定是否传入现有的Database
。有时它是有意义的,如果调用者已经有一个,如你的例子。其他时候,调用者只需执行一个数据库操作,然后通过不打扰调用者负责创建Database
并记住正确处理它来简化API有一些好处。