XML Fields with Entity Framework Code First

ぃ、小莉子 提交于 2019-12-05 01:18:09

问题


I'm using Entity Framework with the Code First model (pet project, and I love editing simple classes and having my schema updated automatically). I have a class like follows:

[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 to me to store Polygons in the database, and be able to query their texture. On the other hand, if I'm saving a polygon with 5,000 points to the database it takes forever to run that many inserts, and honestly, I'm never going to be querying Points except to retrieve an individual Polygon.

What I'd love to do is get rid of "PolygonId" in the "Point" class, get rid of the "Points" table, and have the Polygon table look something like

PolygonId int PK
Texture varchar(255)
Points XML

And then have the points just serialize to a string that is saved directly into the table, yet unserializes back into an array of points. Is there a way to either have EF do this, or to write a custom serializer/deserializer for the field, so at least it seems automatic when used throughout the code-base?

Thanks,

Dan


回答1:


I think that you would have to add another property and write some code to do the 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 just keep the XML property from showing up in Intellisense (when this type is used from a library) and the debugger.



来源:https://stackoverflow.com/questions/17858392/xml-fields-with-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!