none
Mixing WebAPI with EntityFramework and controlling the serialization of a data table RRS feed

  • Question

  • OK 

    I'm new to using the entity framework and am also new to WebAPI 2.0, so this is likely a much simpler question than it seems and I'm stumped.

    I started off building the EF designer using "model first"

    https://docs.microsoft.com/en-us/ef/ef6/modeling/designer/workflows/model-first

    I then built a simple controller using this guide:

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

    and added a simple controller.  

    My problem is that when I'm calling the exposed get method off of the controller it returns in the classes error code indicating that the object failed to serialize because the entity context has been disposed. 

    A very well written version of my problem can be found here:

    https://stackoverflow.com/questions/42874481/exception-on-get-call-on-a-table-using-entity-framework-in-webapi?noredirect=1&lq=1

    and here:

    https://stackoverflow.com/questions/36840348/ef6-the-operation-cannot-be-completed-because-the-dbcontext-has-been-disposed

    The problem with the suggested solutions is that in both cases they are advocating full expansion of the object, when what I want to return is the ID and not the referenced object.

    

            [HttpGet()]
            [Route("test/books")]
            public Book[] GetDetails()
            {
                using (var db = new MyFirstDBEntities())
                {
                    Book[] bs = db.Books.ToArray();
    
                    return bs;
                }
            }
    

    I want to not return the contents of Author nor Subjects, just the book, without the expansion. 

    IOW I'm not looking to user books.Include("Author")

    How can that be done?

    Also, how can I specify a specific level of expansion?  Note that in this model a book can have multiple authors as well an author can have multiple books.  IOW only go one deep?

    Thanks

    -Ken


    Saturday, September 7, 2019 3:38 AM

All replies