如何使用实体框架和工作单元和存储库模式支持全文搜索
How to support full text search using entity framwork and UnitOfWork and Repository pattern
我们正在使用entity framework 6、UnitOfWork 和 Repository 模式。我们有庞大的 table,需要 SQL 的全文支持。所以,有什么简单的方法可以让我们使用 linq 和 entity framework?
查询数据库
例如搜索产品列表:
var itemInformation = UnitOfWork.ProductGs1Repository.RunFullTextContainsQuery(x => x.ItemDescription, searchKeyWords);
您只需要扩展您的存储库 Repository<TEntity>
并添加下面的代码,这样您就可以使用 linq
轻松搜索您的实体
public IEnumerable<TEntity> RunFullTextContainsQuery(Expression <Func <TEntity, object>> property, string search)
{
if ( string.IsNullOrWhiteSpace(search))
{
return Enumerable.Empty<TEntity>();
}
var unaryExpression = property.Body as UnaryExpression;
var memberExpression = property.Body as MemberExpression ?? (unaryExpression != null ? unaryExpression.Operand as MemberExpression : null );
if (memberExpression == null)
{
throw new Exception( string.Format( "Invalid lambda expression: '{0}'.", property));
}
var query = string.Format( "SELECT * FROM {0} WHERE CONTAINS( {1}, @search)", GetTableName(), memberExpression.Member.Name);
return _context.Database.SqlQuery<TEntity>(query, new SqlParameter("@search" , search));
}
private string GetTableName()
{
var objectContext = (( IObjectContextAdapter) _context).ObjectContext;
var sql = objectContext.CreateObjectSet<TEntity>().ToTraceString();
var regex = new Regex( @"FROM\s+(?<table>.+)\s+AS" );
var match = regex.Match(sql);
return match.Groups[ "table"].Value;
}
我们正在使用entity framework 6、UnitOfWork 和 Repository 模式。我们有庞大的 table,需要 SQL 的全文支持。所以,有什么简单的方法可以让我们使用 linq 和 entity framework?
查询数据库例如搜索产品列表:
var itemInformation = UnitOfWork.ProductGs1Repository.RunFullTextContainsQuery(x => x.ItemDescription, searchKeyWords);
您只需要扩展您的存储库 Repository<TEntity>
并添加下面的代码,这样您就可以使用 linq
public IEnumerable<TEntity> RunFullTextContainsQuery(Expression <Func <TEntity, object>> property, string search)
{
if ( string.IsNullOrWhiteSpace(search))
{
return Enumerable.Empty<TEntity>();
}
var unaryExpression = property.Body as UnaryExpression;
var memberExpression = property.Body as MemberExpression ?? (unaryExpression != null ? unaryExpression.Operand as MemberExpression : null );
if (memberExpression == null)
{
throw new Exception( string.Format( "Invalid lambda expression: '{0}'.", property));
}
var query = string.Format( "SELECT * FROM {0} WHERE CONTAINS( {1}, @search)", GetTableName(), memberExpression.Member.Name);
return _context.Database.SqlQuery<TEntity>(query, new SqlParameter("@search" , search));
}
private string GetTableName()
{
var objectContext = (( IObjectContextAdapter) _context).ObjectContext;
var sql = objectContext.CreateObjectSet<TEntity>().ToTraceString();
var regex = new Regex( @"FROM\s+(?<table>.+)\s+AS" );
var match = regex.Match(sql);
return match.Groups[ "table"].Value;
}