GibboK
GibboK

Reputation: 73988

How to update an entity using Entity Framework from Business Layer?

I my web application structured with 3 layers, controller, business logic and repository.

From the BL layer I am updating an entity with the following code. As you can see I am updating property by property.

I would like to know if there is a better way to do it, removing this manual mapping.

---------------------- CONTROLLER

    public IHttpActionResult Put(int id, DeviceDTO dto)
    {
        GaDevice device = Mapper.Map<GaDevice>(dto);
        deviceBLL.Update(id, device);
        return Ok();
    }

---------------------- BL

    public void Update(int id, GaDevice entity)
    {
        bool hasValidId = GetById(id) != null ? true : false;
        if (hasValidId == true)
        {
            GaDevice device = deviceRepo.GetById(id);
            device.CanNotifyPc = entity.CanNotifyPc; // NOT SURE HERE
            device.CanNotifyPrinter = entity.CanNotifyPrinter;
            device.LocationId = entity.LocationId;
            device.Name = entity.Name;
            device.Note = entity.Note;
            device.OperativeFromTime = entity.OperativeFromTime;
            device.OperativeToTime = entity.OperativeToTime;
            deviceRepo.Update(device );
            deviceRepo.Save();
        }

---------------- Repository

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

Upvotes: 0

Views: 104

Answers (1)

Lukas G
Lukas G

Reputation: 680

What about saving the changes made to the context in the Update()? Otherwise, what does your code in the Save() do?

public void Update(GaDevice entity)
{
    context.Entry(entity).State = EntityState.Modified;
    context.SaveChanges();
}

Upvotes: 1

Related Questions