Aleksa
Aleksa

Reputation: 3104

Serializing Entity object

This is the object I try to serialize:

public class EmailAttachment
{
    public int ID { get; set; }
    public string Filepath { get; set; }
    public string Filename { get; set; }

    public int EmailID { get; set; }

    [IgnoreDataMember]
    public virtual ReceivedEmail Email { get; set; }
}

And this is my serialization code:

        var attachments = unitOfWork.EmailAttachmentRepository.Get(e => e.EmailID == emailID);
        return Json(attachments, JsonRequestBehavior.AllowGet);

The problem is that although I put [IgnoreDataMember] attribute, Email property of EmailAttachment is still serialized. I can see entity log in the console, when attachments are fetched first there is no fetching of Email becuase lazy loading is enabled but when return Json(attachments, JsonRequestBehavior.AllowGet); is executed then for every attachment in list Email is fetched from database, and this is propagated on properties of Email.

How can I stop this? I want only EmailAttachment without its virtual properties...

Upvotes: 2

Views: 140

Answers (2)

Alexander Derck
Alexander Derck

Reputation: 14488

You can disable lazy loading when you've created your context, I would suggest modifying your Get method to accept another bool to enable/disable lazyloading:

var attachments = unitOfWork
    .EmailAttachmentRepository.Get(e => e.EmailID == emailID, lazyloading: false);

Then where you create your context:

using(var ctx = new MyContext())
{
       ctx.Configuration.LazyLoadingEnabled = lazyloading;  //false
       ...
}

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

IgnoreDataMemder works for different stack.

In you case you should use ScriptIgnore Attribure

Upvotes: 1

Related Questions