Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repository Pattern: Method signature for Edit/Delete methods

I'm trying to teach myself the repository pattern, and I have a best practices question.

Imagine I have the entity (this is a linq to sql entity but I've stripped all the linq to sql code and the data annotations attributes for clarity):

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public string Telephone { get; set; }
}

The abstract repo for my interface so far is:

public interface IPersonRepository
{
    IQueryable<Person> Person { get; }
    void Add(Person person);
    void SubmitChanges();
    // I want an Edit method here
    // I want a Delete method here
}

My question is this: What would be the method signature for the edit / delete methods? What would be the best practices for these? If Id for example was the only "uneditable" (i.e. the key) property of a Person, how would you implement this?

Should Edit take a Person parameter, and then the edit method code lookup the entity with the supplied id and edit that way?

Should delete take a Person parameter, or simply an id?

I'm trying to think what would be the most logical, clear way to do it, but I'm getting all confused so thought I'd ask!

Thanks!

like image 648
AndrewC Avatar asked May 27 '26 04:05

AndrewC


2 Answers

I generaly have them both (entity and Id) for delete:

void Delete(Person person);
void DeleteById(int personId);

and one with on the entity for save:

void Save(Person person);

You might also consider to make a generic base repository for the standard CRUD actions:

public interface IBaseRepository<T>
{
    T GetById(Guid id);
    IList<T> GetAll();
    void Delete(T entity);
    void DeleteById(Guid id);
    void Save(T entity);
}

If you just need a Save(T entity) or a Insert(T entity) and Update(T entity) depends a little bit on your architecture.

like image 69
Martin Buberl Avatar answered May 28 '26 18:05

Martin Buberl


Your Delete method should look like this.

    void Delete(Person person); 

If you need a more generic approach of the patterns, please take a look at this blog post: Entity Framework Repository & Unit Of Work T4 Template

like image 21
Ramón García-Pérez Avatar answered May 28 '26 19:05

Ramón García-Pérez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!