作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个简单的 EF/MVC 应用程序,我正在尝试实现一些存储库来处理我的实体。我已经设置了一个 BaseObject 类和一个 IBaseRepository 接口(interface)来处理最基本的操作,因此我不必每次都重复:
public abstract class BaseObject<T>
{
public XA.Model.Entities.XAEntities db;
public BaseObject()
{
db = new Entities.XAEntities();
}
public BaseObject(Entities.XAEntities cont)
{
db = cont;
}
public void Delete(T entity)
{
db.DeleteObject(entity);
db.SaveChanges();
}
public void Update(T entity)
{
db.AcceptAllChanges();
db.SaveChanges();
}
}
public interface IBaseRepository<T>
{
void Add(T entity);
T GetById(int id);
IQueryable<T> GetAll();
}
但后来我发现自己必须在每个存储库中实现 3 个基本方法(Add、GetById 和 GetAll):
public class AgencyRepository : Framework.BaseObject<Agency>, Framework.IBaseRepository<Agency>
{
public void Add(Agency entity)
{
db.Companies.AddObject(entity);
db.SaveChanges();
}
public Agency GetById(int id)
{
return db.Companies.OfType<Agency>().FirstOrDefault(x => x.Id == id);
}
public IQueryable<Agency> GetAll()
{
var agn = from a in db.Companies.OfType<Agency>()
select a;
return agn;
}
}
我怎样才能将它们放入我的 BaseObject 类中,这样我就不会与 DRY 发生冲突。
最佳答案
嗨,我遇到了同样的问题。想出这样的解决方案
namespace ABC
{
public class EntitiesRepository<T> : IDisposable where T : class
{
private ObjectContext _context;
/// <summary>
/// The IObjectSet that represents the current entity.
/// </summary>
private ObjectSet<T> _objectSet;
public OperationStatus status { get; set; }
/// <summary>
/// Initializes a new instance of the DataRepository class
/// </summary>
public BilderQuizEntitiesRepository()
{
_context = new Entities(); //DBContext
_objectSet = _context.CreateObjectSet<T>();
}
public T Select(int id)
{
EntityKey key = GetEntityKey(id);
return (T)_context.GetObjectByKey(key);
}
public void Delete(T entity)
{
try
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
EntityKey key = GetEntitySpecificKey(entity);
T attachEntity = (T)_context.GetObjectByKey(key);
_objectSet.DeleteObject(attachEntity);
SaveChanges();
}
catch
{
}
}
public void Delete(int id)
{
EntityKey key = GetEntityKey(id);
Delete((T)_context.GetObjectByKey(key));
SaveChanges();
}
public void Update(T entity)
{
try
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
EntityKey key = GetEntitySpecificKey(entity);
T attachEntity = (T)_context.GetObjectByKey(key);
_objectSet.Attach(attachEntity);
_objectSet.ApplyCurrentValues(entity);
SaveChanges();
}
catch
{
}
}
/// <summary>
/// Returns Entity Key
/// </summary>
/// <param name="keyValue"></param>
/// <returns></returns>
private EntityKey GetEntityKey(object keyValue) //Get EnrityKey
{
var entitySetName = _context.DefaultContainerName + "." + _objectSet.EntitySet.Name;
var keyPropertyName = _objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });
return entityKey;
}
/// <summary>
/// Returns Entity Key
/// </summary>
/// <param name="keyValue"></param>
/// <returns></returns>
private EntityKey GetEntitySpecificKey(T entity) //Get EnrityKey
{
Type objType = typeof(T);
var keyPropertyName = _objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
var pi = objType.GetProperty(keyPropertyName);
var keyValue = pi.GetValue(entity, null);
var entitySetName = _context.DefaultContainerName + "." + _objectSet.EntitySet.Name;
var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });
return entityKey;
}
private string GetPrimaryKeyValue(T entity)
{
Type objType = typeof(T);
var keyPropertyName = _objectSet.EntitySet.ElementType.KeyMembers[0].ToString();
var pi = objType.GetProperty(keyPropertyName);
var keyValue = pi.GetValue(entity, null);
return keyValue.ToString();
}
/// <summary>
/// Saves all context changes
/// </summary>
public bool SaveChanges()
{
return _context.SaveChanges() > 0 ? true : false;
}
/// <summary>
/// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase
/// </summary>
/// <param name="disposing">A boolean value indicating whether or not to dispose managed resources</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
}
}
如果你找到更好的方法,请告诉我
关于c# - 如何在 Entity Framework 应用程序的基类中实现 CRUD 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861346/
我是一名优秀的程序员,十分优秀!