1

I'm returning data through web api with..

FMSEntities db = new FMSEntities();
db.Voucher_BankReceipt.Include(x => x.Status)

Where status is parent table which references other children as given in hashsets below..

public Status()
{
        this.Voucher_BankPayment = new HashSet<Voucher_BankPayment>();
        this.Voucher_BankReceipt = new HashSet<Voucher_BankReceipt>();
        this.Voucher_CashPayment = new HashSet<Voucher_CashPayment>();
        this.Voucher_CashReceipt = new HashSet<Voucher_CashReceipt>();
        this.Voucher_Journal = new HashSet<Voucher_Journal>();
        this.Voucher_Log = new HashSet<Voucher_Log>();
        this.Voucher_Workflow = new HashSet<Voucher_Workflow>();
}

On including the parent table status, it includes all the referenced hashset objects. How can I avoid reloading of Voucher_BankReceipt & other hashset json ?

2
  • As usual: turn off lazy loading. But the option in the answer is more preferable. Commented Dec 15, 2017 at 10:04
  • Did my answer satisfy your question? If so, please consider accepting it. Commented Feb 21, 2018 at 17:08

1 Answer 1

3

The general rule is to NEVER send Entity Framework objects into the Web API JSON Serializer, and you just found out why.

Instead you need to take exactly from EF what you need, or what your API caller needs. There is no way that the Serializer will know that for you. Because of its nature it will almost always grab too much, possibly even with Looping errors as a result.

The solution is to create Objects/ViewModels that copy the parts of the EF Objects that the caller needs, fill those from the EF Objects, and then return them.

A quick-and-dirty way is to use anonymous objects, for example:

// Instead of "return EF_Product;" you can use this:
return new
{
    Product = new
    {
        Id = EF_Product.Id,
        Name = EF_Product.Name
    }
};

A good rule-of-thumb is to only assign simple properties (number, bool, string, datetime) from the EF Objects to the ViewModel items. As soon as you encounter an EF Object property that is yet another EF Object (or a collection of EF Objects), then you need to translate those as well to 'simple' objects that are not linked to EF.

On the other end of the spectrum there are libraries such as AutoMapper. If you decide that you need actual ViewModel classes, then AutoMapper will help mapping the EF Objects to those ViewModels in a very structured way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.