Why is a generic repository considered an anti-pat

2019-04-19 11:59发布

问题:

it seems to me that a lot of specialised repository classes share similar characteristics, and it would make sense to have these classes implement an interface that outlines these characteristics, creating a generic repository

to illustrate my point, say we have this code

public class IEntity
{
    public int Id; 
}

public interface IRepository<T> where T: IEntity
{

    IEnumerable<T> List { get; }
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    T FindById(int Id);
}

[Table("Author")]
public partial class Author : IEntity
{
    public int Id { get; set; }

    [Required]
    public string authorname { get; set; }
}

and then we go onto implement these interfaces to create our specific repositories

public class AuthorRepository : IRepository<Author>
{

    Model1 _authorContext;

    public AuthorRepository()
    {
        _authorContext = new Model1();

    }
    public IEnumerable<Author> List
    {
        get
        {
            return _authorContext.Authors;
        }

    }

    public void Add(Author entity)
    {
        _authorContext.Authors.Add(entity);
        _authorContext.SaveChanges();
    }

    public void Delete(Author entity)
    {
        _authorContext.Authors.Remove(entity);
        _authorContext.SaveChanges();
    }

    public void Update(Author entity)
    {
        _authorContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
        _authorContext.SaveChanges();

    }

    public Author FindById(int Id)
    {
        var result = (from r in _authorContext.Authors where r.Id == Id select r).FirstOrDefault();
        return result; 
    }
}

before i implemented this, i went out a did a bit of research about whether it was a good idea or not, and all the information i could find we statements calling it an anti-pattern but without explaining why.

Why is a generic repository considered an anti-pattern?