【问题标题】:Dynamic Linq SearchFor from entities by Passing Tablename,ColumnName and value as parameter通过传递表名、列名和值作为参数从实体中动态 Linq SearchFor
【发布时间】:2015-05-19 08:47:37
【问题描述】:

我需要在 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;
}

这又不起作用..

有人帮我做这件事。我已经尝试了很长时间.. 非常感谢您的建议。

【问题讨论】:

标签: c# linq entity-framework


【解决方案1】:

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

// 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();
}

【讨论】:

    【解决方案2】:

    您可以从您的 dbcontext 执行 sql 查询:

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

    【讨论】:

    • 这将是一个非常非常糟糕的解决方案。如果用户查询名为; truncate table Customers-- 的表,则查询将按原样传递到数据库而不转义。不惜一切代价避免这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多