【发布时间】:2016-09-04 19:15:39
【问题描述】:
我有三个项目
- MVC Web 应用程序
- 一种两层业务/存储库的服务应用程序
- 实体框架(所有 EF 配置都在这里)
MVC参考>服务
服务参考 > EF
我目前有这三种方法可以做一些工作。
public bool StoreUpload<T>(UploadInformation information)
where T : class, IUploadEntity { }
public bool RemoveUpload<T>(UploadInformation information)
where T : class, IUploadEntity { }
public bool CommitUpload<T>(UploadInformation information)
where T : class, IUploadEntity { }
我使用这些委托给上述工作方法的接口从我的控制器调用这三个方法:
Boolean StoreUpload(UploadInformation information);
Boolean RemoveUpload(UploadInformation information);
Boolean CommitStoredDocuments(UploadInformation information);
基于来自开关中 UploadTypes 枚举的条件,我调用了正确的工作方法。我这样做是因为我不希望我的 mvc 项目能够访问 EF 数据库类型,否则我知道有人将开始从整个应用程序中查询数据。我将这些 switch 语句用于所有接口方法:
public bool StoreUpload(UploadInformation information)
{
switch (information.Type)
{
case UploadTypes.AutoIncident:
return RemoveUpload<AutoIncident>(information);
case UploadTypes.Incident:
return RemoveUpload<IncidentInjury>(information);
case UploadTypes.Inspection:
return RemoveUpload<Inspection>(information);
case UploadTypes.OtherIncident:
return RemoveUpload<OtherIncident>(information);
default:
return false;
}
}
public bool RemoveUpload(UploadInformation information) { ... }
public bool CommitStoredUpload(UploadInformation information) { ... }
此方法可能会稍微说明类型参数的用途。我正在使用 EF 以通用方式更新表格。
private bool CommitStoredDocuments<T>(UploadInformation information) where T : class, IUploadEntity
{
var uploads = GetStoredUploads(information.UniqueId);
var entity = db.Set<T>().Include(e => e.Uploads)
.Single(e => e.UniqueId == information.UniqueId);
entity.Uploads.AddRange(uploads);
...
}
如果能够将需要类型参数的工作方法作为委托传递给切换工作方法调用,那就太好了。
public bool DoSomeWork(delegateMethod, information) {
switch(information.Type) {
case UploadTypes.AutoInciden:
return delegateMethod<AutoIncident>(information);
...
}
}
这可以吗? 另外,我在为这个问题构建一个好的标题时遇到了麻烦,所以如果这些是描述挑战的更好方式,请发表评论。
【问题讨论】:
-
如果
DoSomeWork方法已经拥有对正确方法的引用(使用delegateMethod),为什么还要再次使用switch子句? -
我从无权访问这些类型的层调用。
标签: c# asp.net-mvc entity-framework generics delegates