Search code examples
asp.net-mvccrud

CRUD in MVC repository


I have created a repository data layer in my MVC web application, and want to use it for my CRUD methods. But I came to think of situations where I want to do something like:

If record does not exist
   create record
else
   update record

But how does this fit into CRUD? Is this two-in-one operation logic supposed to be kept in the controller?


Solution

  • I think the repository should take care of that, the controller should be as light as possible:

    At repository level:

    public bool CreateUpdate(Type model)
    {
        var record = db.FirstOrDefault(x=> x.Id == model.Id);
        if(record == null)
        {
            Create(model);
        }
        else
        {
            Update(model);
        }
    }
    
    public bool Create(Type model)
    {
        //create logic here
    }
    
    public bool Update(Type model)
    {
        //update logic here
    }