kez
kez

Reputation: 2313

generic function to search a value in a table, with multiple DBcontexts

I have the following search function for the search for duplicate values

    public bool isRecordExisting(string newValue) 
    {
        bool isExisting = false;

        using (var db = new SampleEntities_1()) 
        {
            var res = db.SAMPLE_TABLE.Where(x => x.SAMPLE_COLUMN == newValue).First();

            if (res != null) {
                isExisting = false;
            }

        }
        return isExisting;
    }

I got a few DbInstances

  1. SampleEntities_1
  2. SampleEntities_2
  3. SampleEntities_3

Therefore I trying to make this function a generic one, like following

    public bool isRecordExisting(string newValue, string column, DbSet<T> tableName, DbContext dbcontextname) 
    {
        bool isExisting = false;

        using (var db = new dbcontextname()) 
        {
            var res = db.tableName.Where(x=>x.column = newValue).First();

            if (res != null) 
            {
                isExisting = false;
            }
            
        }
        return isExisting;
    }

so I can call this function like this

var result = isRecordExisting("Bob", "SAMPLE_COLUMN", "SAMPLE_TABLE", SampleEntities_1);

can I know this approach possible or not, already I have compilation errors :(

  1. 'dbcontextname' is a variable but is used like a type

  2. 'SampleEntities_1' is a type, which is not valid in the given context

Upvotes: 0

Views: 24

Answers (1)

Filipe
Filipe

Reputation: 161

You could use a Generic repository, or a factory type pattern, etc..

Example, if you want to create a Generic Repository in your case, then something like this:

public class GenericRepo<TEntity, TContext> : IGenericRepo<TEntity>, IDisposable where TEntity : class where TContext : DbCOntext, new()
{ 
     public TContext Context;
     public GenericRepo(DbContext)
     {
         Context = dbContext as TContext;
     }

     public virtual TEntity Get(Expression<Func<TEntity, bool>> where = null)
     {
         Context.Set<TEntity>.FirstOrDefault(where);
     }
}

Then maybe something like this:

   public bool isRecordExisting(string newValue, string column) 
    {
        bool isExisting = false;

        using (var db = new GenericRepo<EntityType, SampleEntities_1>()) 
        {
            var res = db.Get(x => x.column == newValue);

            if (res != null) 
            {
                isExisting = false;
            }
            
        }

        return isExisting;
    }

Although you can pass the column and tablename essentially this way ^, you still need to create an instance of the GenericRepo for each DBContext. Same with the factory pattern. You could try what Salomon Zhang mentioned in the comments.

Also, note: Always use async code for accessing the DB.

Upvotes: 1

Related Questions