开发者

Asp.net MVC 2 Entity Framework Generic Repository method. How to update a specific column?

I have 10 tables with the same design. Each of them have an IsActive colu开发者_开发知识库mn.

For example:

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 explains how to update a specific column.

Thanks everyone.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜