Question

I'm using code first EF 5 with this class.

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

When I use a context to save an object in MyObject property, it correctly saves serialized data into the DB.

When I load the entity from the context:

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

MyObject property is null. How can I load this property?

Was it helpful?

Solution

You're missing the else clause or return statement in the setter. This will cause MyObject to always be set to null.

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

        return;
    }

    MyObject = null;
}

Reformatted for clarity:

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

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

    return;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top