gpt4 book ai didi

c# 通用存储库类

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:33 26 4
gpt4 key购买 nike

我有各种具有 DeleteEntity 方法的存储库类:

public void DeleteEntity(int Key)
{
try
{
ObjectParameter error = new ObjectParameter("Error", typeof(string));
context.proc_BorrarChofer(Key, error);
if (error.Value.ToString() != "")
{
Errores myerror = new Errores();
myerror.ID = 100;
myerror.Descripcion = error.Value.ToString();
MyErrors.Add(myerror);
}
}
catch (DbUpdateConcurrencyException ex)
{
// Update the values of the entity that failed to save from the store
ex.Entries.Single().Reload();
// status = ex.Message;
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = ex.Message.ToString();
MyErrors.Add(myerror);

}
catch (DbUpdateException ex)
{
string status = (ex.InnerException.InnerException != null) ? ex.InnerException.InnerException.Message : "";
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = status;
MyErrors.Add(myerror);
}
catch (Exception ex)
{
//paso los errores
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = ex.Message.ToString();
MyErrors.Add(myerror);
}

现在每个 Repository 类都有相同的方法。只有存储过程的名称发生变化。如何制作通用删除方法并将其作为参数 sp Name 传递?

谢谢!!!

最佳答案

在你的位置,我会使用模板设计模式重新制作这段代码

public abstract class BaseRepository
{
protected abstract void DeleteEntityWithProcedure(int key, ObjectParameter error);

public void DeleteEntity(int Key)
{
try
{
ObjectParameter error = new ObjectParameter("Error", typeof(string));
DeleteEntityWithProcedure(key, error);
if (error.Value.ToString() != "")
{
Errores myerror = new Errores();
myerror.ID = 100;
myerror.Descripcion = error.Value.ToString();
MyErrors.Add(myerror);
}
}
catch (DbUpdateConcurrencyException ex)
{
// Update the values of the entity that failed to save from the store
ex.Entries.Single().Reload();
// status = ex.Message;
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = ex.Message.ToString();
MyErrors.Add(myerror);

}
catch (DbUpdateException ex)
{
string status = (ex.InnerException.InnerException != null) ? ex.InnerException.InnerException.Message : "";
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = status;
MyErrors.Add(myerror);
}
catch (Exception ex)
{
//paso los errores
Errores myerror = new Errores();
myerror.ID = 1000;
myerror.Descripcion = ex.Message.ToString();
MyErrors.Add(myerror);
}
}

您的具体存储库将是这样的

public class CustomerRepository:BaseRepository
{
protected override DeleteEntityWithProcedure(int key, ObjectParameter error)
{
//execute procedure you needed
//context.proc_BorrarChofer(Key, error);
}
}

执行您的自定义存储库

var customerRepository = new CustomerRepository();
customerRepository.DeleteEntity(1);

关于c# 通用存储库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com