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();
}