0

I am trying to Update an Entry in my DB. First, here is my code:

The Beverage

public class Beverage
{
    [Key]
    public int BeverageID { get; set; }

    public string BeverageName { get; set; }

    public HashSet<BeverageAdditive> Additive { get; set; } = new HashSet<BeverageAdditive>();
}

The Additive:

public class Additive : IPickerFriendlyModel, IBeverageType
{
    [Key]
    public int AdditiveID { get; set; }

    public string AdditiveName { get; set; }

    public ICollection<BeverageAdditive> Beverage { get; set; } = new HashSet<BeverageAdditive>();
}

The BeverageAdditive:

public class BeverageAdditive
{
    // Is a ForeignKey
    public int BeverageID { get; set; }

    // Is a ForeignKey
    public int AdditiveID { get; set; }

    [JsonIgnore]
    public Beverage Beverage { get; set; }

    [JsonIgnore]
    public Additive Additive { get; set; }
}

The Controller:

public class BeverageController : Controller
{
    // PUT: api/Beverage/5
    [HttpPut("{id}")]
    public IActionResult Put(int id, [FromBody]Beverage bev)
    {
        try
        {
            if (bev == null)
            {
                return BadRequest();
            }

            // Get the existing Beverage
            var item = GetByID(bev.BeverageID);
            if (item == null)
            {
                return NotFound();
            }

            // Update the values
            Context.Entry(item).CurrentValues.SetValues(bev);

            // Save the changes
            Context.SaveChanges();

            // Return everything done as expected
            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex);
        }
    }
}

I will call this Api via Curl:

curl -X PUT --header 'Content-Type: application/json-patch+json' --header 'Accept: text/html' -d '{ \ 
"beverageID": 91, \ 
"beverageName": "Test3", \ 
"additive": [ \ 
 { \ 
   "beverageID": 91, \ 
   "additiveID": 4 \ 
 }, \ 
 { \ 
   "beverageID": 91, \ 
   "additiveID": 2 \ 
 } \ 
], \ 
}' 'http://localhost:9001/api/Beverage/91'

The problem is, that the Table BeverageAllergen does not getting updated (nor does it insert the new Additives) and I do not get an Exception. The values stay the same.

Does anyone know what is causing this?

Thanks for your help!

DirtyNative
  • 2,553
  • 2
  • 33
  • 58
  • Possible duplicate of [Using the Entry().CurrentValues.SetValues() is not updating collections](https://stackoverflow.com/questions/11705569/using-the-entrytentity-currentvalues-setvalues-is-not-updating-collections) – Isaac Kleinman Feb 14 '18 at 16:52

1 Answers1

1

So I finally figured out how it works. You have to delete and add the Entites by hand, so a working code will be something like this:

public class BeverageController : Controller
{
// PUT: api/Beverage/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Beverage bev)
{
    try
    {
        if (bev == null)
        {
            return BadRequest();
        }

        // Get the existing Beverage
        var item = GetByID(bev.BeverageID);
        if (item == null)
        {
            return NotFound();
        }

        // Update the values
        Context.Entry(item).CurrentValues.SetValues(bev);

            // ####################################################
            // ######### This is where the magic happens ##########

            // If theres a records that have a 0 as ID, remove them
            bev.Additive.RemoveWhere(add => add.AdditiveID <= 0);

            // Remove the already exising Additives
            RemoveAllAdditives(item);

            // Add the Additives
            for (int i = 0; i < bev.Additive.Count; i++)
            {
                AddAdditive(item, bev.Additive.ElementAt(i).AdditiveID);
            }
            // #####################################################


        // Save the changes
        Context.SaveChanges();

        // Return everything done as expected
        return Ok();
    }
    catch (Exception ex)
    {
        return BadRequest(ex);
    }
}
}
    private void AddAdditive(Beverage item, int additiveID)
    {
        var add = new AdditiveController(Context).GetByID(additiveID);

        if (add == null)
        {
            return;
        }

        var bevAdd = new BeverageAdditive()
        {
            Beverage = item,
            Additive = add
        };
        item.Additive.Add(bevAdd);
    }

    private void RemoveAdditive(Beverage bev, int additiveID)
    {
        var beva = bev.Additive.Where(bevAdd => bevAdd.BeverageID == bev.BeverageID && bevAdd.AdditiveID == additiveID).FirstOrDefault();
        bev.Additive.Remove(beva);
        Context.SaveChanges();
    }

    private void RemoveAllAdditives(Beverage bev)
    {
        for (int n = 0; n < bev.Additive.Count; n++)
        {
            RemoveAdditive(bev, bev.Additive.ElementAt(n).AdditiveID);
            n--;
        }
    }

Hope this helps someone facing the same problem as I did

DirtyNative
  • 2,553
  • 2
  • 33
  • 58