I need to write a function called IsExists(string TableName,string KeyColumnName,string ValueToCheck) in a DAL that checks if data exists in a specific table and in the specific column that I pass
Basically, I want to achieve something similar when I try to execute a sql query
select count(id) from "+TableName+" where "+keyColumnName+"="+ValueToCheck+";
But I can not use sql query ..
In my solution, I have a .edmx file, an entity class along with a repository class that has a SearchFor method:
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); } }
I tried something like this
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; }
Which doesn't work again.
Someone help me with this. I tried for a long time. Suggestions are greatly appreciated.
source share