实体框架5二进制对象保存,但始终加载null

时间:2014-04-22 15:23:52

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

我在这个类中首先使用代码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属性为null。如何加载此属性?

1 个答案:

答案 0 :(得分:1)

您在设置器中缺少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;
}