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"

    I then built a simple controller using this guide:

    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:

    and here:

    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.


            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?



    Saturday, September 7, 2019 3:38 AM

All replies