简体   繁体   English

如何从C#Web API DbSet获取实际对象?

[英]How to get actual objects from C# Web API DbSet?

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 response.Content.ReadAsAsync doesn't handle the references). 问题是:服务器给了我一个包含$ ids和$ refs的JSON,所以我的列表最终成为一个对象,其余的为null(因为response.Content.ReadAsAsync不处理引用)。

Please help. 请帮忙。 I just want some straight up donut objects man. 我只想要一些笔直的甜甜圈对象。 None of this $ref icing or $id filling. $ ref结冰或$ id填充均无效。

My server side controller: 我的服务器端控制器:

public class DonutController : ApiController
{
    private DonutEntities db = new DonutEntities();

    // GET api/PackageEvent/since/{datetime}
    public IEnumerable<Donut> GetDonutsSince([FromUri] String datetime) {
        List<Donut> donuts = null;
        DateTime dt = DateTime.Parse(datetime);

        //return db.Donuts.Where(d => d.When > dt).AsEnumerable();

        String sql = @"
            SELECT *
            FROM Donuts
            WHERE [Donuts].[When] > CAST(@datetime AS DATETIME)
        ";

        object[] parameters = new object[] {
            new SqlParameter("@datetime", DateTime.Parse(datetime).ToString(CultureInfo.InvariantCulture))
        };

        List<Donut> results = db.Donuts.SqlQuery(sql, parameters).ToList();
        if (results.Any()) {
            donuts = results;
        }

        return donuts.AsEnumerable();
    }
}

My client side request method: 我的客户端请求方法:

    public static IEnumerable<Donut> 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<Donut> donuts = response.Content.ReadAsAsync<IEnumerable<Donut>>().Result;

        return donuts;
    }

So it turns out that the solution was to use Json.NET . 因此,事实证明,解决方案是使用Json.NET It handles the $id and $ref attributes, and actually creates a list populated with objects. 它处理$ id和$ ref属性,并实际上创建一个填充有对象的列表。

New client side request method: 新的客户端请求方法:

public static IEnumerable<Donut> 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;
    String responseContent = response.Content.ReadAsStringAsync().Result;

    IEnumerable<Donut> events = JsonConvert.DeserializeObject<IEnumerable<Donut>>(responseContent);

    return donuts;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM