C# 使用多个DBContext搜索表中的值的通用函数
我有以下搜索功能来搜索重复的值C# 使用多个DBContext搜索表中的值的通用函数,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我有以下搜索功能来搜索重复的值 public bool isRecordExisting(string newValue) { bool isExisting = false; using (var db = new SampleEntities_1()) { var res = db.SAMPLE_TABLE.Where(x => x.SAMPLE_COLUMN == newValue).Fir
public bool isRecordExisting(string newValue)
{
bool isExisting = false;
using (var db = new SampleEntities_1())
{
var res = db.SAMPLE_TABLE.Where(x => x.SAMPLE_COLUMN == newValue).First();
if (res != null) {
isExisting = false;
}
}
return isExisting;
}
我有几个实例
public bool isRecordExisting(string newValue, string column, DbSet<T> tableName, DbContext dbcontextname)
{
bool isExisting = false;
using (var db = new dbcontextname())
{
var res = db.tableName.Where(x=>x.column = newValue).First();
if (res != null)
{
isExisting = false;
}
}
return isExisting;
}
我能知道这种方法是否可行吗?我已经有编译错误:(
您可以使用通用存储库或工厂类型模式等 例如,如果您想在您的案例中创建一个通用存储库,那么如下所示:
public class GenericRepo<TEntity, TContext> : IGenericRepo<TEntity>, IDisposable where TEntity : class where TContext : DbCOntext, new()
{
public TContext Context;
public GenericRepo(DbContext)
{
Context = dbContext as TContext;
}
public virtual TEntity Get(Expression<Func<TEntity, bool>> where = null)
{
Context.Set<TEntity>.FirstOrDefault(where);
}
}
public bool isRecordExisting(string newValue, string column)
{
bool isExisting = false;
using (var db = new GenericRepo<EntityType, SampleEntities_1>())
{
var res = db.Get(x => x.column == newValue);
if (res != null)
{
isExisting = false;
}
}
return isExisting;
}
公共类GenericRepo:IGenericRepo,IDisposable where tenty:class where TContext:DbCOntext,new()
{
公共语境;
公共通用报告(DbContext)
{
Context=dbContext作为TContext;
}
公共虚拟TEntity Get(表达式where=null)
{
Context.Set.FirstOrDefault(其中);
}
}
那么可能是这样的:
public class GenericRepo<TEntity, TContext> : IGenericRepo<TEntity>, IDisposable where TEntity : class where TContext : DbCOntext, new()
{
public TContext Context;
public GenericRepo(DbContext)
{
Context = dbContext as TContext;
}
public virtual TEntity Get(Expression<Func<TEntity, bool>> where = null)
{
Context.Set<TEntity>.FirstOrDefault(where);
}
}
public bool isRecordExisting(string newValue, string column)
{
bool isExisting = false;
using (var db = new GenericRepo<EntityType, SampleEntities_1>())
{
var res = db.Get(x => x.column == newValue);
if (res != null)
{
isExisting = false;
}
}
return isExisting;
}
public bool isRecordExisting(字符串newValue,字符串column)
{
bool isExisting=false;
使用(var db=new GenericRepo())
{
var res=db.Get(x=>x.column==newValue);
如果(res!=null)
{
i存在=错误;
}
}
返回是存在的;
}
虽然基本上可以通过这种方式传递列和表名^,但仍然需要为每个DBContext创建GenericRepo的实例。与工厂模式相同。您可以尝试Salomon Zhang在评论中提到的方法
另外,请注意:始终使用异步代码访问数据库。首先,假设不同的数据库具有不同的表,对吗?如果
表名
不在数据库中,则会导致错误。其次,使用(var DB=new DbContext())
这应该修复您的第一个错误吗?但我希望将列
,表名
,dbcontextname
作为参数传递