Entity First XML Fields

I use the Entity Framework with the Code First model (a pet project, and I like to edit simple classes and automatically update the schema). I have a class like:

[Table("Polygons")] public class Polygon { public int PolygonId { get; set; } public String Texture { get; set; } public virtual ICollection<Point> Points { get; set; } } [Table("Points")] public class Point { public int PolygonId { get; set; } public double X { get; set; } public double Y { get; set; } } 

It’s useful for me to store polygons in a database and be able to query their texture. On the other hand, if I save a polygon with 5,000 points in the database, it always runs a lot of inserts, and, frankly, I will never ask for Points, except to get a separate Polygon.

What I would like to do is get rid of the "PolygonId" in the "Point" class, get rid of the "Points" table, and the Polygon table looks something like this:

 PolygonId int PK Texture varchar(255) Points XML 

And then the points are simply serialized into a row, which is stored directly in the table, but is not esterized back into an array of points. Is there a way to either EF do this, or write my own serializer / deserializer for the field, so that at least it seems automatic when used across the codebase?

Thanks,

Dan

+4
source share
1 answer

I think that you will need to add another property and write code for serialization.

This should do it:

 [Table("Polygons")] public class Polygon { public int PolygonId { get; set; } public String Texture { get; set; } [NotMapped] public virtual ICollection<Point> Points { get; set; } [Column("Points")] [EditorBrowsable(EditorBrowsableState.Never)] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string PointsXml { get { var serializer = new XmlSerializer(typeof (List<Point>)); using (var stringWriter = new StringWriter()) { serializer.Serialize(stringWriter, Points.ToList()); stringWriter.Flush(); return stringWriter.ToString(); } } set { var serializer = new XmlSerializer(typeof(List<Point>)); using (var stringReader = new StringReader(value)) { Points = (List<Point>) serializer.Deserialize(stringReader); } } } } 

The EditorBrowsable and DebuggerBrowsable attributes are optional and will simply store the XML property in Appellisense (when this type is used from the library) and the debugger.

+6
source

Source: https://habr.com/ru/post/1493430/


All Articles