gpt4 book ai didi

c# - 通过将表名、列名和值作为参数从实体进行动态 Linq SearchFor

转载 作者:太空狗 更新时间:2023-10-29 22:02:03 24 4
gpt4 key购买 nike

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

这又是行不通的..

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

最佳答案

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

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

关于c# - 通过将表名、列名和值作为参数从实体进行动态 Linq SearchFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30320809/

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