ADO EF 数据操作方法
我希望有人能指出我重构一些方法以接受泛型类型的方向。
我有一个服务与我的数据库中的许多不同的表进行交互。大多数表格的格式相同。该服务对所有表执行相同的基本操作:GetAll、Save、Delete。由于操作是相同的,我一直在寻找一种创建核心操作库的方法。
这是我的保存功能的示例,它与其他表的唯一区别是数据。所以这里是 ClientData,下一个是 GroupData 等...
internal static void SaveClient(ClientData clientData)
{
using (CFOEntityModelContainer database = new CFOEntityModelContainer())
{
if (!IsClientValid(clientData.Id))
{
database.Clients.AddObject(ConvertClientDataToClient(clientData));
database.SaveChanges();
}
else
{
Client client = database.Clients.First(
c => c.Id == clientData.Id);
client.Name = clientData.Name;
database.SaveChanges();
}
}
}
建议?
I was hoping someone could point me in the direction of refactoring some of my methods to accept generic types.
I have a Service that speaks with many different tables in my database. The majority of the tables are of the same format. The service performs the same basic operations on all of the tables, GetAll, Save, Delete. Since the operation is the same I was looking for a way to create a core library of actions.
This is an example of my save function, the only difference between this and that of the other tables is the data. So here its ClientData, on the next one its GroupData ect...
internal static void SaveClient(ClientData clientData)
{
using (CFOEntityModelContainer database = new CFOEntityModelContainer())
{
if (!IsClientValid(clientData.Id))
{
database.Clients.AddObject(ConvertClientDataToClient(clientData));
database.SaveChanges();
}
else
{
Client client = database.Clients.First(
c => c.Id == clientData.Id);
client.Name = clientData.Name;
database.SaveChanges();
}
}
}
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的方法包含特定于类型的操作,您希望如何使其通用?您是否总是有 XXX 实体和 XXXData 类,其中 XXX 实体包含
Id
和Name
,XXXData 类包含Name
和Id
>?如果不是,您的通用保存将只是模板接受特定方法的委托=没有简化。如果是,您可以执行以下操作:首先准备通用方法中使用的接口:
现在在实体和数据类上实现该接口并创建通用方法:
您可以像这样调用此方法:
How do you expect to make it generic if your method contains type specific operations? Do you always have XXX entity and XXXData class where XXX entity contains
Id
andName
and XXXData class containsName
andId
? If not your generic save would be just template accepting delegates to specific method = no simplification. If yes you can do something like:First prepare interface used in generic methods:
Now implement that interface on your entity and data classes and create generic method:
You can call this method like: