Your first statement can be rewritten as
bool dispose = db == null;
and the second as
db = db ?? new DatabaseContainer();
See the null-coalescing operator for this last option.
Vra
I have this method where I may pass a DbContext or I may not:
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(); }
}
}
I am doing 2 ternary operations, 1 to determine if I should do a dispose and another to determine if I need to create a new dbContext.
Question: Both ternary ops are the exact same condition (db == null)
, is there a way I can set my dispose
and my db
variables in one op?
Oplossing
Your first statement can be rewritten as
bool dispose = db == null;
and the second as
db = db ?? new DatabaseContainer();
See the null-coalescing operator for this last option.
Ander wenke
You can use dispose
in second check:
db = (dispose ? new DatabaseContainer() : db);
or use null-coalescing operator:
db = db ?? new DatabaseContainer();
Sounds like you want to dispose db
if you were responsible for creating it, but use the one passed and do not dispose if not. You could do something like:
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();
}
}
You could even skip the db =
and do a one-liner:
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();
}
}
But I'm not sure how much readability any of this gets you.