Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get actual objects from C# Web API DbSet?
    text
    copied!<p>I'm trying to get a list of 'recent' donuts that have been added to the box (database) since I last checked. I'm a fatty and want some delicious noms. The problem: the server is giving me JSON that is full of $ids and $refs, so my list ends up being one object, with the rest as null (because <code>response.Content.ReadAsAsync</code> doesn't handle the references).</p> <p>Please help. I just want some straight up donut objects man. None of this $ref icing or $id filling.</p> <p><strong>My server side controller:</strong></p> <pre><code>public class DonutController : ApiController { private DonutEntities db = new DonutEntities(); // GET api/PackageEvent/since/{datetime} public IEnumerable&lt;Donut&gt; GetDonutsSince([FromUri] String datetime) { List&lt;Donut&gt; donuts = null; DateTime dt = DateTime.Parse(datetime); //return db.Donuts.Where(d =&gt; d.When &gt; dt).AsEnumerable(); String sql = @" SELECT * FROM Donuts WHERE [Donuts].[When] &gt; CAST(@datetime AS DATETIME) "; object[] parameters = new object[] { new SqlParameter("@datetime", DateTime.Parse(datetime).ToString(CultureInfo.InvariantCulture)) }; List&lt;Donut&gt; results = db.Donuts.SqlQuery(sql, parameters).ToList(); if (results.Any()) { donuts = results; } return donuts.AsEnumerable(); } } </code></pre> <p><strong>My client side request method:</strong></p> <pre><code> public static IEnumerable&lt;Donut&gt; GetDonutsSince(DateTime dt) { HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") }; api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); String url = "Donut/since?datetime=" + dt; HttpResponseMessage response = api.GetAsync(url).Result; Console.WriteLine(response.Content.ReadAsStringAsync().Result); // outputs the raw json with $ids and $refs IEnumerable&lt;Donut&gt; donuts = response.Content.ReadAsAsync&lt;IEnumerable&lt;Donut&gt;&gt;().Result; return donuts; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload