Как использовать Dapper с производными типами ⇐ C#

Место общения программистов C#
Anonymous
Как использовать Dapper с производными типами

Сообщение Anonymous »

У меня есть около 20 классов, производных от ModelBase (которые содержат общие вещи, такие как CreationDate, Id и т. д.).
Использование Dapper , эти производные классы легко сохранять и удалять (вся работа выполняется предпоследней строкой)
public static bool ModelDelete(ModelBase model, SqlConnection? conn = null, SqlTransaction? trans = null)
{
bool connectionIsNew = (conn is null);
bool transactionIsNew = (trans is null);

try
{
if (connectionIsNew)
conn = new SqlConnection(Globals.connString);

if (conn is null)
{
throw new Exception("Unable to establish a database connection in Data.ModelDelete");
return false;
}
else
{
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
}

if (transactionIsNew)
trans = conn.BeginTransaction();

DynamicParameters p = new DynamicParameters();
p.Add("Id", model.Id, DbType.Int32);
p.Add("Error", null, DbType.String, ParameterDirection.Output, 8000);
string spName = $"sp{model.GetType().Name}_Delete";
int recordsAffected = conn.Execute(spName, p, trans);
}
catch (Exception exc)
{ }
}

Но, похоже, я не могу сделать то же самое с помощью Get/Fetch и в итоге получим
public static ModelBase ModelGet(Type t, int id, SqlConnection? conn = null, SqlTransaction? trans = null, bool withDependents = false)
{
bool connectionIsNew = (conn is null);
bool transactionIsNew = (trans is null);
ModelBase model = default!;

try
{
if (connectionIsNew)
conn = new SqlConnection(Globals.connString);

if (conn is null)
{
throw new Exception("Unable to establish a database connection in Data.ModelGet");
}
else
{
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();

if (transactionIsNew)
trans = conn.BeginTransaction();

var p = new { Id = id };

string spName = $"sp{t.Name}_Get";

switch (t.Name)
{
case nameof(Account):
model = conn.QuerySingle(spName, p, trans);
break;

case nameof(AccountGroup):
model = conn.QuerySingle(spName, p, trans);
break;

case nameof(Address):
model = conn.QuerySingle(spName, p, trans);
break;

case nameof(Agency):
model = conn.QuerySingle(spName, p, trans);
break;


and so on with all the different derived model classes. This works but is inelegant. Is there a better way than having a separate `conn.QuerySingle` for each of my derived classes?


Подробнее здесь: https://stackoverflow.com/questions/791 ... ived-types

Вернуться в «C#»