gpt4 book ai didi

c# - 我想在存储库模式中执行通用搜索选项

转载 作者:行者123 更新时间:2023-12-02 15:11:01 25 4
gpt4 key购买 nike

这里我实现了通用存储库模式以同时进行 CRUD 操作,我也想做搜索选项,任何人都可以告诉我查询来做通用搜索选项,我的代码在下面

public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
T GetById(object Id);
T Insert(T obj);
void Delete(object Id);
T Update(T obj);
void Save();
long Count();
}
public class Repository<T> : IRepository<T> where T : class
{
private PegasusPlusEntities context;
private DbSet<T> dbSet;
public Repository()
{
context = new PegasusPlusEntities();
dbSet = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return dbSet.ToList();
}
public T GetById(object id)
{
return dbSet.Find(id);
}
public T Insert(T obj)
{
dbSet.Add(obj);
Save();
return obj;
}
public void Delete(object id)
{
T entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public void Delete(T entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public T Update(T obj)
{
dbSet.Attach(obj);
context.Entry(obj).State = EntityState.Modified;
Save();
return obj;
}
public long Count()
{
return dbSet.Count();
}

public void Save()
{
try
{
context.SaveChanges();

}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{


}
}
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (context != null)
{
context.Dispose();
context = null;
}
}
}
}

提前致谢...

最佳答案

有几种方法可以做到这一点,但这里是一个简单的例子

向当前接口(interface)添加一个方法以允许进行通用搜索

IEnumerable<T> Search(Expression<Func<T,bool>> predicate);

一个简单的实现看起来像这样

public IEnumerable<T> Search(Expression<Func<T,bool>> predicate) {
return dbSet.Where(predicate).ToList();
}

使用它的一个例子是

var repository = new Repository<Person>();
var searchResults = repository.Search(p => p.FirstName == "John" && p.LastName == "Doe");

关于c# - 我想在存储库模式中执行通用搜索选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43911851/

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