views:

187

answers:

1

I have 10 tables with the same design. Each of them has an IsActive Collumn.
EX:
Category
CatID
CatName
IsActive

Product
PrdID
PrdName
IsActive

Is there a way to create a generic method to update the IsActive column.

 public void Deactivate<T>(T TEntity)
    {
        //Put the code to update 
        //IsActive
    }

I Read about Generic Repository , but nothing explain how to update a specific Collumn.
Thanks everyone.

+3  A: 

The trick is to put a where type restriction for your generic type on your BaseRepository class. Try something similar to this:

WARNING: air code ;-)

Base model:

public interface IDbTable
{
    bool IsActive { get; set; }
}

public class DbTable
{
    public bool IsActive { get; set; }
}

Your model

public class Category : DbTable
{
    public int CatId { get; set; }
    public string CatName { get; set; }
}

public class Product : DbTable
{
    public int PrdId { get; set; }
    public string PrdName { get; set; }
}

Your repository

public interface IBaseRepository<T> where T : class, IDbTable
{
    void Deactivate<T>(T entity);
}

public class BaseRepository<T> : IBaseRepository
{
    public void Deactivate<T>(T entity)
    {
        entity.IsActive = false;
    }
}

You could go even further and extend your IDbTable to include even more generic and helpful columns. E.g.

public interface IDbTable
{
    int Id { get; set; }
    bool IsActive { get; set; }
    DateTime UpdatedOn { get; set; }
    DateTime CreatedOn { get; set; }
}

Repo

public interface IBaseRepository<T> where T : class, IDbTable
{
    T GetById(int id);
    void Add(T entity);
    void Update(T entity);
    void Deactivate(T entity);
}

public class BaseRepository<T> : IBaseReposiotry<T>
{
    public T GetById(int id)
    {
        //code to get the entity by id
    }

    public void Add(T entity)
    {
        entity.CreatedOn = DateTime.UtcNow;
        entity.UpdatedOn = DateTime.UtcNow;
    }

    public void Update(T entity)
    {
        entity.UpdatedOn = DateTime.UtcNow;
    }

    public void Deactivate(T entity)
    {
        entity.IsActive = false;
    }
}

These two articles should help you out as well:
new Repository().DoMagic()
Implementing a Simple Generic Repository with LinqToSql

HTHs,
Charles

Charlino
This is exacly what I need, thanks Charlino for the answer.Now I want be able to create a Generic Query for the update. The only thing differents for each query is the Table Name .
Jean-Francois