最好的方法将取决于您的依赖关系。POCO/核心组件是否依赖于 EF?您是否将 Access to DB 注入到您的核心库程序集中?等等
我个人使用 repository/luw 模式,其中各种存储库对象继承自通用的基本存储库对象。DAL 依赖于 EF,但核心中的 POCO 类不依赖。
存储库子类具有特定的类型,并执行 OTHER OBEJCT 业务检查。需要检查其他实体的 IE 业务规则,我在 DAL 中实现。
存储库类属于数据访问层项目,并且 DO 依赖于 EF 并注入了上下文。下面的例子。
特定于我在 POCO 上执行的实例的检查。我通过在基类存储库类上实现的接口执行需要数据库访问的检查,该存储库类又根据要求被覆盖。所以现在在添加或更改对象时会触发CheckEntity调用。
例如...注意删除了一些代码以保持示例相关...
public class RepositoryEntityBase<T> : IRepositoryEntityBase<T>, IRepositoryEF<T> where T : BaseObject
public virtual OperationStatus Add(T entity)
{
var opStatus = new OperationStatus(status: true, operation: OperationType.Add);
try
{
if (OnBeforeAdd != null) // registered listeners of added event?
{
var evtArg = PrepareEventArgs(entity, MasterEventType.Create);
OnBeforeAdd(this, evtArg);
}
opStatus = CheckBeforePersist(entity);
if (opStatus.Status)
{
Initialize(entity);
EntityDbSet.Add(entity);
if (OnAfterAdd != null) // registered listeners of added event?
{
var evtArg = PrepareEventArgs(entity, MasterEventType.Create);
OnAfterAdd(this, evtArg);
}
}
}
catch (Exception ex)
{
opStatus.SetFromException("Error Adding " + typeof(T), ex);
}
return opStatus;
}
//... then in a specific repository class
//... irepositorybase expects Check before persist.
public override OperationStatus CheckBeforePersist(MasterUser entity)
{
// base entity rule check first
var opStatus = new OperationStatus(true, OperationType.Check);
opStatus.ValidationResults = base.CheckEntity(entity);
if (opStatus.ValidationResults.Count > 0)
{
opStatus.Status = false;
opStatus.Message = "Validation Errors";
return opStatus;
}
//now check the local memory
var masterUser = Context.Set<MasterUser>().Local //in context
.Where(mu => mu.Id != entity.Id // not this record
&& mu.UserName == entity.UserName ) // same name
.FirstOrDefault();
if (masterUser != null)
{
opStatus.Status = false;
opStatus.Message = "Duplicate UserName :" + masterUser.UserName + " UserId:"+ masterUser.Id.ToString();
return opStatus;
}
masterUser = Context.Set<MasterUser>().Local //in context
.Where(mu => mu.Id != entity.Id // not this record
&& mu.Email == entity.Email) // same email
.FirstOrDefault();
if (masterUser != null)
{
opStatus.Status = false;
opStatus.Message = "Duplicate Email :" + masterUser.Email + " Username:" + masterUser.UserName;
return opStatus;
}
// now check DB
masterUser = Get(mu => mu.Id != entity.Id //not this record being checked
&& mu.UserName == entity.UserName); // has same username
if (masterUser != null)
{
opStatus.Status = false;
opStatus.Message = "Duplicate UserName :" + masterUser.UserName + " UserId:"+ masterUser.Id.ToString();
return opStatus;
}
masterUser = Get(mu => mu.Id != entity.Id // not this record
&& mu.Email == entity.Email); // but same email
if (masterUser != null)
{
opStatus.Status = false;
opStatus.Message = "Duplicate Email:" + masterUser.Email + " UserName:"+ masterUser.UserName;
return opStatus;
}
return opStatus;
}
}