通过将Tablename,ColumnName和value作为参数传递来实体的动态Linq SearchFor

时间:2015-05-19 08:47:37

标签: c# linq entity-framework

我需要在DAL中编写一个名为IsExists(string TableName,string KeyColumnName,string ValueToCheck)的函数,它检查数据是否存在于特定表中以及我传递的特定列中

基本上我想在我尝试使用sql查询时实现类似的东西

select count(id) from "+TableName+" where "+keyColumnName+"="+ValueToCheck+";

但是我不能使用sql查询..

在我的解决方案中,我有一个.edmx文件,一个实体类以及一个存储库类,它有SearchFor方法:

public class EntityRepository<C, TEntity> : IEntityRepository<TEntity>
        where TEntity : class
        where C : DbContext
{
    public IQueryable<TEntity> SearchFor(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
    {
        return _entities.Set<TEntity>().Where(predicate);
    }
}

我试过这样的事情

public bool CheckIsExists<T>(string keyColumnName, string valueToCheck) where T : class
{
    bool isExist = false;

    using (var repository = ContextFactory.CreateEmployeeMasterRepository())
    {
        var repo = repository.GetEntityRepository<T>();
        object obj = (T)Activator.CreateInstance(type);
        repo.SearchFor(u => u.GetType().GetProperty(keyColumnName).GetValue(obj).ToString() == valueToCheck);
    }
    return isExist;
}

哪个再次无效......

有人帮助我这样做。我一直在努力...建议非常感谢。

2 个答案:

答案 0 :(得分:0)

以下是我将如何解决此类问题。如果您愿意,可以将其转换为函数。

// Let's say I have a Customers table and want to search against its Email column
// First I get my data layer class that inherits from DbContext class
yourContextClass db = new yourContextClass();
// below I am getting valueToCheck from a view with GET method
public ActionResult Index(string valueToCheck)
{
 bool isExists = false;
 IEnumerable<Customers> customersList = (from cus in db.Customers select cus).ToList();
 int index = customersList.FindIndex(c => c.Email == valueToCheck);
 if (index >= 0) 
  isExists = True;
 // if index is -1 then the value to check does not exist
return View();
}

答案 1 :(得分:-1)

您可以从dbcontext执行sql查询:

using (var ctx = new DBEntities())
{
   var itemsCount = ctx.Database.SqlQuery<int>("select count(id) from "+TableName+" where "+keyColumnName+" = "+ValueToCheck+").FirstOrDefault<int>();
}