代码之家  ›  专栏  ›  技术社区  ›  Jean-Francois

Asp.netmvc2实体框架通用存储库方法。如何更新特定列?

  •  0
  • Jean-Francois  · 技术社区  · 14 年前

    IsActive 列。

    例如:

     CatID 
     CatName 
     IsActive
    

    产品

    PrdID
    PrdName
    IsActive
    

    有没有办法创建一个泛型方法来更新 活跃的 列。

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

    谢谢大家。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Charlino    14 年前

    诀窍是把 where BaseRepository

    基本型号:

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

    你的模型

    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; }
    }
    

    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;
        }
    }
    

    您可以更进一步,扩展IDB表以包含更多通用和有用的列。例如。

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

    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;
        }
    }
    

    这两篇文章也应该对您有所帮助:
    new Repository().DoMagic()
    Implementing a Simple Generic Repository with LinqToSql

    HTHs公司,