c# - How to set an Object as the value in JSON string Using Asp.Net Web API? -


i building jeopardy web api application prepare .net technical interviews.

i using code first entity framework create database.

i using fiddler test posts/gets

i have 2 tables: categories , jeopardyquestion.

a question can have 1 category, , category can have many questions. model setups below.

public class jeopardyquestion {     [databasegenerated(databasegeneratedoption.identity)]     public int  jeopardyquestionid { get; set; }      [required]     public string question { get; set; }      [required]     public string answer { get; set; }      [required]     public int value { get; set; }      [required]     public virtual category category { get; set; }  }  public class category {     [databasegenerated(databasegeneratedoption.identity)]     public int categoryid { get; set; }      [required]     public string categoryname { get; set; }       public virtual list<jeopardyquestion> jeopardyquestions { get; set; }  } 

i able post 2 categories: ado.net , asp.net. 2 categories have empty list of questions.

my error comes when try post new question , try apply existing category it:

 {"question" : "this framework allows developers create web applications","answer" : "what asp.net", "value" : "200", "category" : "asp.net"} 

error

 {"message":"the request invalid.","modelstate":{"jeopardyquestion.category":["error converting value \"asp.net\" type 'jeopardy.models.category'. path 'category', line 1, position 152.","the category field required."]}} 

my question is, how correctly set key/value pair in json, when value needs object? in case, category object?

more specifically, how do

 "category" : "asp.net" 

where asp.net in categoryname column in category table in database?

add categoryid field question entity , send that. let actual category null. in addition may consider creating dto objects sending data , service , have regular c# code in controllers copy data entities. helps when shape of data want expose different shape of data in database or when there parts of data should not exposed.


Comments