我有这种方法,我可以传递DbContext,或者我可能不会:
public static List<ClaimService> GetServicesForAccountType(DatabaseContainer db,Guid claimId, Guid accountTypeId)
{
bool dispose = (db == null ? true :false);
try
{
db = (db == null ? new DatabaseContainer(): db);
return db.Database.SqlQuery<ClaimService>("SELECT * FROM dbo.ClaimService WHERE ClaimId = '@p1' AND AccountTypeId = '@p2'", new System.Data.SqlClient.SqlParameter("p1", claimId), new System.Data.SqlClient.SqlParameter("p2", accountTypeId)).ToList();
}
finally
{
if (dispose) { db.Dispose(); }
}
}
我正在做两个三元操作,1确定我是否应该进行一次处理,另一个确定是否需要创建一个新的dbContext。
问题:两个三元操作都是完全相同的条件(db == null)
,有没有办法在一个操作中设置dispose
和我的db
变量?
答案 0 :(得分:2)
您可以在第二次检查中使用dispose
:
db = (dispose ? new DatabaseContainer() : db);
或使用null-coalescing operator:
db = db ?? new DatabaseContainer();
答案 1 :(得分:2)
您的第一个陈述可以改写为
bool dispose = db == null;
和第二个
db = db ?? new DatabaseContainer();
有关最后一个选项,请参阅null-coalescing operator。
答案 2 :(得分:1)
听起来你想要处理db
,如果你负责创建它,但是使用通过的那个,如果没有,则不要处置。你可以这样做:
public static List<ClaimService> GetServicesForAccountType(DatabaseContainer db,Guid claimId, Guid accountTypeId)
{
DatabaseContaner localScopeDbContainer = null;
try
{
db = db ?? (localScopeDbContainer = new DatabaseContainer());
return db.Database.SqlQuery<ClaimService>("SELECT * FROM dbo.ClaimService WHERE ClaimId = '@p1' AND AccountTypeId = '@p2'", new System.Data.SqlClient.SqlParameter("p1", claimId), new System.Data.SqlClient.SqlParameter("p2", accountTypeId)).ToList();
}
finally
{
if (localScopeDbContainer != null)
localScopeDbContainer.Dispose();
}
}
你甚至可以跳过db =
并做一行:
public static List<ClaimService> GetServicesForAccountType(DatabaseContainer db,Guid claimId, Guid accountTypeId)
{
DatabaseContaner localScopeDbContainer = null;
try
{
return (db ?? (localScopeDbContainer = new DatabaseContainer()).Database.SqlQuery<ClaimService>("SELECT * FROM dbo.ClaimService WHERE ClaimId = '@p1' AND AccountTypeId = '@p2'", new System.Data.SqlClient.SqlParameter("p1", claimId), new System.Data.SqlClient.SqlParameter("p2", accountTypeId)).ToList();
}
finally
{
if (localScopeDbContainer != null)
localScopeDbContainer.Dispose();
}
}
但我不确定这对你有多大的可读性。