How do I Update the data in related tables in EF Core API from Controller's PUT Method by searching LaureateId or PrizeId as per above model classes?

Sarwar Akbar 31 Reputation points
2022-07-18T12:01:39.917+00:00

public class Prize
{
[Key]
public int PrizeId { get; set; }
public string Year { get; set; }
public string Category { get; set; }
public List<Laureate> Laureates { get; set; }

     public string OverallMotivation { get; set; }  
 }  
  
 public class Laureate  
 {  
     [Key]  
     public int LaureateId { get; set; }  
     public string RemoteIdentifier { get; set; }  
     public string Firstname { get; set; }  
     public string Surname { get; set; }  
     public string Motivation { get; set; }  
     public string Share { get; set; }  
     public int PrizeId { get; set; }  
     public Prize Prize { get; set; }  
 }  

How do I Update the data in related tables in EF Core API from Controller's PUT Method by searching LaureateId or PrizeId as per above model classes?
Below is my Code in PUT Method. Please tell where I am doing wrong?

[HttpPut]
[Route("update/{id}")]
public string Update(int id, Prize prize1)
{
var data = db.Prizes.Include(c => c.Laureates).FirstOrDefault(g => g.PrizeId == id);

        data.Year = prize1.Year;  
        data.Category = prize1.Category;  
        data.OverallMotivation = prize1.OverallMotivation;              
          
        db.SaveChanges();  
        return "Prize Updated";  
    }
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,415 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,309 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,146 Reputation points
    2022-07-18T21:31:12.417+00:00

    From the above query I am able to find the properties of Prize Class by Intellisense but not able to find the properties of Laureate class.

    I'm not sure if you are referring to the query results "data" or the Prize prize1 input parameter. There is not a single Laureate class in the results set. You've specifically defined a collection - a navigation property. You can either loop over the collection or use an index to get to a single Laureate class.

    Collections (C#)
    EF Core Relationships

    This is an example NOT a solution.

    // PUT api/<PrizeController>/5  
    [HttpPut("{id}")]  
    public ActionResult<Prize> Put(int id, [FromBody] Prize prize1)  
    {  
        Models.Prize data = db.Prizes  
            .Include(l => l.Laureates)  
            .FirstOrDefault(p => p.PrizeId == id);  
      
        //loop over the results  
        //does nothing  
        foreach(var laureate in data.Laureates)  
        {  
            string f = laureate.Firstname;  
        }  
      
        //Pick a specific result  
        //does nothing  
        string f2 = data.Laureates[0].Firstname;  
      
        //return the data result set  
        return Ok(data);  
    }  
    

    If you are trying to assing prize1.Laureates to the data.Laureates, then see your previous post where I showed you how to do this when populating the tables from a JSON file. Similar to the previous example the Prize prize1 should be a view model. And, the results should be a View model not an entity.

    https://learn.microsoft.com/en-us/answers/questions/916313/deserialialize-the-json-file-amp-seed-it-in-the-sq.html

    I recommend that you go through a few tutorials to learn the basics.


1 additional answer

Sort by: Most helpful
  1. AgaveJoe 26,146 Reputation points
    2022-07-24T11:12:33.797+00:00

    Can we use "?? String.Empty" in laureate extension method to store null value in database like below... I tried this but it throws ArgumentNullException: Value cannot be null. (Parameter 'source').

    Most likely the client code that calls the Put method passes an empty Laureates parameter. You did not share this part of the code or explain the use case so the community can only guess how the code works. I recommend using the Visual Studio debugger to see if the Laureates parameter is null and reviewing the client code that calls the Put.

    The standard programming pattern in Web API (REST) is updating (HTTP Put) one record at a time. In other words, update the Prize record not the collection of Laureates navigation properties too. If you want to update a Laureate record than create a Laureate controller. The reasoning is there must be a requirement which explains exactly what to do with each record within the Laureates collections during an update. What if the Laureates collection contains a record that does not exist in the table? What if the Laureates collection has one record and the database has two? Or perhaps the business rule states the Laureates records must be replaced with the Laureates collection passed to the Put action? What are your rules?

    Again it is important that you take the time to learn standard Web API and REST programming patterns which are openly published. Research REST on the internet and go through online Web API tutorials. Learning standard patterns and practices is a much quicker path than making up your own patterns.

    0 comments No comments