0

I would like to save in the database a custom type property which is a class.

The property to save is myProperty with the type CustomTypeClass in the below example:

public class Test
{
    private CustomTypeClass myProperty;

    public CustomTypeClass MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}

So, the value to save in the database is the result of the ToString override method:

public class CustomType
{
    public int Start { get; set; }
    public int End { get; set; }

    public CustomType(int start, int end)
    {
        this.Start = start;
        this.End = end;
    }

    public override string ToString()
    {
        return "[" + this.Start + "," + this.End + "]";
    }
}

I would like to perform the following code for saving in the database:

CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value;

database.Add(test);
database.SaveChanges();

How can I do this ?

At the moment, I get the following error:

Unsupported field-type 'CustomTypeClass' found for field 'myProperty' of class 'Test'. 

Maybe you did not specify the TransientAttribute for this field or the PersistentAttribute is not specified for the referenced class. [class=Test]
CaptJak
  • 3,592
  • 1
  • 29
  • 50
profou
  • 197
  • 1
  • 17

1 Answers1

0

I don't think you'll be able to do that since it's not a known attribute within the database. However, What I've done in the past is something like:

//Save logic:
CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value.ToString();

database.Add(test);
database.SaveChanges();

And then create a static method on CustomType to convert it from a string back to an object:

var obj = db.Tests.First();
var customType = CustomType.LoadFromString(obj.myProperty);

Where LoadFromString is a static method on the object and converts it from a string back into an object (by parsing the string).

Brian Mains
  • 50,520
  • 35
  • 148
  • 257