【问题标题】:Entity Framework 5 binary object saves, but always loads nullEntity Framework 5 二进制对象保存,但始终加载 null
【发布时间】:2014-04-22 15:23:51
【问题描述】:

我在这个类中使用代码优先 EF 5。

public class MyEvent
{
    public int Id{ get; set; }
    public object MyObject { get; set; }
    public byte[] SerlializedObject
    {
        get
        {
            if (MyObject != null)
            {
                IFormatter formatter = new BinaryFormatter();
                using (var ms = new MemoryStream())
                {
                    formatter.Serialize(ms, MyObject );
                    return ms.ToArray();
                }
            }
            else
            {
                return null;
            }
        }
        set
        {
            if (value.Length > 0)
            {
                IFormatter formatter = new BinaryFormatter();
                using (var ms = new MemoryStream(value))
                {
                    MyObject = formatter.Deserialize(ms);
                }

            }
            MyObject = null;
        }
    }

当我使用上下文在 MyObject 属性中保存对象时,它会正确地将序列化数据保存到数据库中。

当我从上下文加载实体时:

MyEvent e = db.MyEvents.Where(x => x.Id== myId).FirstOrDefault();

MyObject 属性为空。如何加载此属性?

【问题讨论】:

  • SerializedObject 的设置器将始终将 MyObject 设置为 null
  • 我需要结对编程......谢谢。

标签: c# entity-framework binary entity-framework-5


【解决方案1】:

您在 setter 中缺少 else 子句或 return 语句。这将导致MyObject 始终设置为null

set
{
    if (value.Length > 0)
    {
        IFormatter formatter = new BinaryFormatter();
        using (var ms = new MemoryStream(value))
        {
            MyObject = formatter.Deserialize(ms);
        }

        return;
    }

    MyObject = null;
}

为了清晰起见重新格式化:

set
{
    if (0 >= value.Length)
    {
        MyObject = null;
        return;
    }

    IFormatter formatter = new BinaryFormatter();
    using (var ms = new MemoryStream(value))
    {
        MyObject = formatter.Deserialize(ms);
    }

    return;
}

【讨论】:

  • 对!出于某种原因,我正在寻找其他地方......谢谢。
猜你喜欢
  • 2013-06-24
  • 2021-11-06
  • 2021-06-24
  • 2014-10-09
  • 1970-01-01
  • 2020-07-14
  • 2021-09-24
  • 1970-01-01
  • 2014-10-13
相关资源
最近更新 更多