Mil*_*idi 3 c# asp.net generics asp.net-mvc entity-framework
我正在开发一个Asp.Net MVC应用程序,我正在尝试编写一个通用方法来检查DB中是否存在实体,或者使用传递的entityId来实现此方法.如下所示:
public bool CheckIfUserExistsByUserId(int userId)
{
return _userRepository.DbSet().Any(u => u.Id == userId);
}
Run Code Online (Sandbox Code Playgroud)
但是此方法仅检查_userRepository并接受整数作为entityId.
我的问题是我想把这个泛型方法作为我的BaseService中的一般方法,就像我在下面写的其他常规方法一样:
public class BaseService<TModel> : IBaseService<TModel> where TModel : class
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBaseRepository<TModel> _baseRepository;
public BaseService(IUnitOfWork unitOfWork, IBaseRepository<TModel> baseRepository)
{
_unitOfWork = unitOfWork;
_baseRepository = baseRepository;
}
public BaseService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public void Add(TModel entity)
{
this._baseRepository.Add(entity);
}
public void Remove(TModel entity)
{
this._baseRepository.Remove(entity);
}
/// <summary>
/// Remove All Provided Items At Once .
/// </summary>
/// <param name="itemsToRemove"></param>
public void RemoveRange(IEnumerable<TModel> itemsToRemove)
{
_baseRepository.RemoveRange(itemsToRemove);
}
public TModel FindById<T>(T key)
{
return _baseRepository.FindById(key);
}
public void Commite()
{
this._unitOfWork.Commite();
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,我无法从Entity Framework获取传递给我的方法的实体的主键字段.此外,我不想在我使用上述方法的任何地方将实体的主键字段传递给我的方法.是否有可能在EF中获取实体的主键字段?
编辑:根据其他用户的要求,我在下面添加了我的IBaseRepository代码:
public interface IBaseRepository<TModel> where TModel : class
{
/// <summary>
/// Add New Entity .
/// </summary>
/// <param name="entity"></param>
void Add(TModel entity);
/// <summary>
/// Remove Item From Database .
/// </summary>
/// <param name="entity"></param>
void Remove(TModel entity);
/// <summary>
/// Remove All Provided Items At Once .
/// </summary>
/// <param name="itemsToRemove"></param>
void RemoveRange(IEnumerable<TModel> itemsToRemove);
/// <summary>
/// Get The Underlying Type's DbSet .
/// </summary>
/// <returns></returns>
DbSet<TModel> DbSet();
/// <summary>
/// Find Item By Id .
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
TModel FindById<T>(T key);
}
Run Code Online (Sandbox Code Playgroud)
您想要的是查看实体记录是否存在的通用方法.您可以使用类的Any()方法DBSet,并将条件传递给搜索记录.
public bool CheckIfEntityExistsByEntityId<T>(Expression<Func<T,bool>> expr)
{
return _baseRepository.DbSet().Any(u => expr);
}
Run Code Online (Sandbox Code Playgroud)