How to Set Some of Entity Properties in Repository in C#?

試著忘記壹切 提交于 2019-12-01 09:02:07

Alright so you have to make a clear IRepository and make it as simple as possible like this(since you want this Generic):

IRepository:

public interface IRepository<T>
{
    void Add(T entity);
    void Delete(T entity);
    void Delete(int id);
    T GetById(int id);
    IEnumerable<T> GetAll();
    void Update(T entity);
    void save();
}

And Create One Generic Repository like below:

public class Repository<T> : IRepository<T>
    where T : EntityBase
{

    internal MyDbContext context;
    internal DbSet<T> dbSet;
    public Repository()
    {

        context = new MyDbContext();
        this.dbSet = context.Set<T>();

    }

    public void Add(T entity)
    {
        dbSet.Add(entity);
    }

    public void Delete(T entity)
    {
        dbSet.Remove(entity);
    }

    public void Delete(int id)
    {
        dbSet.Remove(dbSet.Find(id));
    }

    public T GetById(int id)
    {
        return dbSet.Find(id);
    }

    public IEnumerable<T> GetAll()
    {
       return dbSet.AsEnumerable();
    }

    public void Update(T entity)
    {
        dbSet.Attach(entity);
        context.Entry(entity).State = EntityState.Modified;
    }

    public void save()
    {
        context.SaveChanges();
    }
}

Good thing about EntityBase is since all of your properties have an id, you can easily go like this:

public class EntityBase
{
    public int id { get; set; }
}

And then implement this to your Models :

public class Example : EntityBase
{

public byte RecordStatus { get; set; }
public string RecordStatusDescription { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDateTime { get; set; }
public string CreatorIPAddress { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDateTime { get; set; }
public string ModifierIPAddress { get; set; }
public string RemovedBy { get; set; }
public string RemovedDateTime { get; set; }
public string RemoverIPAddress { get; set; }
public bool IsRemoved { get; set; }

}

Advantage of using this simple Repository is you can easily do anything with it e.g. :

public class HomeController : Controller
{

    Repository<Example> _repository = new Repository<Example>();


    public ActionResult Index()
    {
        vm.Example = _repository.GetAll()
            .Where(x => x.RecordStatusDescription == "1").ToList(); 
        return View("index",vm);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!