Why is a generic repository considered an anti-pattern? [closed]

落爺英雄遲暮 提交于 2019-12-22 03:16:19

问题


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 were statements calling it an anti-pattern but without explaining why.

Why is a generic repository considered an anti-pattern?

来源:https://stackoverflow.com/questions/31516310/why-is-a-generic-repository-considered-an-anti-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!