Web API未返回特定的实体列表

时间:2018-07-05 00:57:45

标签: c# asp.net-web-api2

我仅对edm框架中的BOOKS实体感兴趣。 但是我和BOOKS实体一起得到了一些其他实体。

这是我的Web API控制器

public class BooksController : ApiController
{
    private MyECommerceDBEntities db = new MyECommerceDBEntities();

    // GET: api/Books
    [ResponseType(typeof(BOOKS))]
    public IQueryable<BOOKS> GetBOOKS()
    {
        return db.BOOKS.OrderByDescending(x => x.BOOKID).Skip(977).Take(5).AsQueryable<BOOKS>();
    }
}

这是我返回的JSON字符串

[{"$id":"1","PRODUCTS":{"$id":"2","MOVIES":[],"ORDERITEMS":[],"PRODUCTDETAILS":[],"SUBCATEGORIES":{"$id":"3","CATEGORIES":{"$id":"4","SUBCATEGORIES":[{"$ref":"3"},{"$id":"5","CATEGORIES":{"$ref":"4"},"PRODUCTS":[],"SUBCATEGORYID":2,"CATEGORYID":1,"SUBCATEGORY":"Kindle Edition","DESCRIPTION":"Kindle EBook"}],"CATEGORYID":1,"CATEGORY":"Books","DESCRIPTION":"Books"},"PRODUCTS":[{"$ref":"2"},{"$id":"6","MOVIES":[],"ORDERITEMS":[],"PRODUCTDETAILS":[],"SUBCATEGORIES":{"$ref":"3"},"REVIEWS":[],"SELLERS_PRODUCTS":[],"CART":[],"BOOKS":[{"$id":"7","PRODUCTS":{"$ref":"6"},"BOOKID":1,"PRODUCTID":1964,"ISBN10":"ISBN-10: 1-934356-43","ISBN13":"ISBN-13: 978-1-93435","BOOKNAME":"Agile Coaching","DESCRIPTION":"","AUTHOR":null,"PUBLISHER":null,"PAGES":"236","BOOKIMAGE":"Agile `Coaching.jpeg","PUBLISHEDDATE":null}],"PRODUCTID":1964,"SUBCATEGORYID":1,"NAME":"Agile Coaching","DESCRIPTION":"","PRICE":0.0},{"$id":"8","MOVIES":[],"ORDERITEMS":[],"PRODUCTDETAILS":[],"SUBCATEGORIES":{"$ref":"3"},"REVIEWS":[],"SELLERS_PRODUCTS":[],"CART":[],"BOOKS":`

2 个答案:

答案 0 :(得分:1)

在响应中序列化实体时,它可能包括实体的导航属性。

尽量避免直接从实体框架直接返回实体。

仅使用要返回给呼叫者的相关信息来创建DTO模型。

简单的例子

//Book model
public class Book {
    public int BookKId { get; set; }
    public int ProductId { get; set; }
    public string ISBN10 { get; set; }
    public string ISBN13 { get; set; }
    public string BookName { get; set; }
    //...other properties
}

从操作返回时,将实体映射到模型

 // GET: api/Books
[ResponseType(typeof(Book[]))]
public IHttpActionResult GetBOOKS() {
    var books = db.BOOKS.OrderByDescending(x => x.BOOKID).Skip(977).Take(5)
    .Select(book => new Book {
        BookKId = book.BOOKID,
        BookName = book.BOOKNAME
        //...other properties
    })
    .ToArray();
    return Ok(books);
}

答案 1 :(得分:0)

除了以上来自Nkosi的答案,这是EF Core中不同类型的加载的说明。

https://docs.microsoft.com/en-us/ef/core/querying/related-data