序列化实体对象

时间:2016-03-22 10:27:05

标签: c# asp.net json entity-framework serialization

这是我尝试序列化的对象:

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; }
}

这是我的序列化代码:

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

问题在于,虽然我添加了[IgnoreDataMember]属性,但Email的{​​{1}}属性仍然是序列化的。我可以在控制台中看到实体日志,当首先获取附件时,没有提取EmailAttachment因为启用了延迟加载,但是当执行Email时,列表return Json(attachments, JsonRequestBehavior.AllowGet);中的每个附件都是从数据库中获取,并在Email的属性上传播。

我怎么能阻止这个?我只想要Email没有虚拟属性......

2 个答案:

答案 0 :(得分:1)

id1 = Column(BIGINT(unsigned=True).with_variant(Integer, "sqlite"), primary_key=True, sqlite_autoincrement=True) id2 = Column(Integer, ForeignKey('table2.id'), primary_key=True, sqlite_autoincrement=False) 适用于不同的堆栈。

在你的情况下,你应该使用ScriptIgnore Attribure

答案 1 :(得分:1)

您可以在创建上下文时禁用延迟加载,我建议您修改Get方法以接受另一个bool启用/禁用延迟加载:

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

然后在哪里创建上下文:

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