gpt4 book ai didi

c# - 如何在 Entity Framework 应用程序的基类中实现 CRUD 操作?

转载 作者:行者123 更新时间:2023-11-30 18:08:54 25 4
gpt4 key购买 nike

我正在开发一个简单的 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/

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