1

I have the following:

// Day Class
public class Day {
    [Key]
    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("playlists")]
    public virtual List < Playlist > playlists { get; set; }
}

// Schedule Class
public class Schedule {
    [Key]
    public int id { get; set; }

    public virtual List < Day > days { get; set; }

    [Required]
    public string hash { get; set; }
}

// Playlist Class
public class Playlist {
    [Key]
    public int id { get; set; }

    [Required]
    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("media")]
    public virtual List < Media > media { get; set; }

    // Media class
    public class Media {
        ...
    }

I am using Web API, SQL / EF to create CRUD operations on the above classes. However, my issue is that when I POST to /schedules/ I'd like all the related properties to update. I am POSTING a raw JSON object and I can parse it properly. The problem is that if I have a media object in the database with a unique key hash or any other object in the db the POST fails with a key duplicate exception since it is trying to re-add the object. I'd like to update the relationships in that scenario... What should I be doing to correct this?

Please ask if you need any other info. Thanks in advance.

EDIT

  [ResponseType(typeof(Schedule))]
        public async Task<IHttpActionResult> PostSchedule([FromBody]Object model)
        {
            var jsonSchedule = model.ToString();
            try
            {
                var _schedule = JsonConvert.DeserializeObject<Schedule>(jsonSchedule);

                db.Schedules.Add(_schedule);
                await db.SaveChangesAsync();

                return Ok();
            }
Community
  • 1
  • 1
user1027620
  • 2,745
  • 5
  • 37
  • 65
  • @JenishRabadiya I've updated the question. – user1027620 Dec 11 '15 at 02:57
  • @JenishRabadiya It does... This works as expected – user1027620 Dec 11 '15 at 03:24
  • 1
    If you are editing the parent and and adding/editing/deleting child items at the same time, you need to update your object graph and its not a trivial task. You may find [this answer](http://stackoverflow.com/a/33509039/3110834) helpful. – Reza Aghaei Dec 11 '15 at 03:36
  • Also you are using `db.Schedules.Add` that tries to insert the entity and all it's children to database. – Reza Aghaei Dec 11 '15 at 03:37
  • You should get your entity from the database (with the id) and then update it with the new values. This way your entity remain attached to the DbContext. – Thomas Dec 11 '15 at 03:58
  • @RezaAghaei The answer seems very helpful. However, I have two other layers (nested objects), what should I do in this case? – user1027620 Dec 11 '15 at 04:02
  • If you are only editing child items in all levels, you can simply mark them as edited. But if you add/edit/delete in all levels, the case is really complicated and you should follow such approach that I did step by step in the [answer](http://stackoverflow.com/a/33509039/3110834) – Reza Aghaei Dec 11 '15 at 04:05
  • You can avoid such complicated edit if you use ajax and commit changes on each request (add/edit/delete). – Reza Aghaei Dec 11 '15 at 04:07
  • By the way, it would be great if you kindly vote for that answer, if you find that helpful. This way that will be more useful for future readers. – Reza Aghaei Dec 11 '15 at 04:08
  • @RezaAghaei sure I will, could you please elaborate a bit on using ajax on each request? You mean I handle relationships using separate calls? – user1027620 Dec 11 '15 at 04:11
  • @RezaAghaei also please note that in my case i'm posting the initial object initially so it doesn't exist in the database yet. – user1027620 Dec 11 '15 at 04:14
  • So you can show `Day` page and let the user enter the name and click save, after the user clicked save, you can save the day in database and show an empty list of `Schedules` that the user can click add for it, and when he clicked add, you can show a dialog to him to enter schedule fields and let him save. After he saved, he can add `Playlist` or edit the `Schedule` or delete the `Schedule` or add new `Schedule`. Continue this pattern until the end of your graph. – Reza Aghaei Dec 11 '15 at 04:19
  • @RezaAghaei Thing is, Media objects already exist in the database... I need to do handle the relationship updates programatically... – user1027620 Dec 11 '15 at 04:21
  • No problem, Follow that pattern, and let the user choose media items from an autocomplete or dropdownlist. If you follow such pattern, then the question would be **How to add an existing media item to an existing playlist** and the answer will be **simply load both of them, then `playlist.media.Add(existingMedia)` then `db.SaveChanges()`** – Reza Aghaei Dec 11 '15 at 04:25

0 Answers0