I try to write a XML<>Object Mapper for my Entity Framework Code First class. Because EF doesn’t support this automatic XML Serialization at the moment I did this to access the “Profile” object property and manipulate the underlying ProfileData string:
[Column(TypeName = "xml")]
public string ProfileData { get; set; }
[NotMapped]
public Profile Profile
{
get { return ProfileData.DeserializeXml<Profile>(); }
set { ProfileData = value.SerializeXml(); }
}
Everything works fine but ProfileData.DeserializeXml() returns (of course) a new object, serialized from the ProfileData string. I think the extension method isn’t relevant for my question but I post it anyway:
public static T DeserializeXml<T>(this string xml) where T : class, new()
{
if(string.IsNullOrWhiteSpace(xml)) return new T();
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
try { return (T)serializer.Deserialize(reader); }
catch { return null; }
}
}
When I want to change my object I do this:
var profile = myObject.Profile;
profile.fooVar = "test";
But this will not affect my myObject until I do this:
myObject.Profile = profile;
I know why but I don’t want to do this, I want a… let us say “direct reference” to the underlying ProfileData string with my object wrapper.
Any idea to archive this or is not possible?
Why doesn’t your class keep a reference to the
Profileobject instead, and only serialize or deserialize when requested? In other words, change it to: