我想在数据库中保存一个类的自定义类型属性。
要保存的属性为myProperty
,其类型为CustomTypeClass
,如下例所示:
public class Test
{
private CustomTypeClass myProperty;
public CustomTypeClass MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
}
因此,要保存在数据库中的值是ToString
覆盖方法的结果:
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 + "]";
}
}
我想执行以下代码以保存在数据库中:
CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value;
database.Add(test);
database.SaveChanges();
我该怎么做?
目前,我收到以下错误:
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]
答案 0 :(得分:0)
我认为你不能这样做,因为它不是数据库中的已知属性。但是,我过去所做的就是:
//Save logic:
CustomType value = new CustomType(3, 5);
Test test = new Test();
test.myProperty = value.ToString();
database.Add(test);
database.SaveChanges();
然后在CustomType上创建一个静态方法,将其从字符串转换回对象:
var obj = db.Tests.First();
var customType = CustomType.LoadFromString(obj.myProperty);
其中LoadFromString是对象上的静态方法,并将其从字符串转换回对象(通过解析字符串)。