-1

我有这个方法,我可能会传递一个 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(); }
    }
}

我正在执行 2 个三元操作,1 个确定是否应该进行 dispose,另一个确定是否需要创建新的 dbContext。

问题:两个三元操作的条件完全相同(db == null),有没有办法可以在一个操作中设置我的dispose和我的db变量?

4

3 回答 3

2

您可以dispose在第二次检查中使用:

db = (dispose ?  new DatabaseContainer() : db);

或使用空合并运算符:

db = db ?? new DatabaseContainer();
于 2014-03-08T02:56:51.557 回答
2

您的第一个语句可以重写为

bool dispose = db == null;

第二个为

db = db ?? new DatabaseContainer();

有关最后一个选项,请参阅null-coalescing 运算符。

于 2014-03-08T02:56:58.783 回答
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();
    }
}

但我不确定这能给你带来多少可读性。

于 2014-03-08T03:00:30.147 回答