将对列表存储在一个表EF中

时间:2014-04-21 15:23:53

标签: c# entity-framework asp.net-mvc-4 database-design ef-code-first

我使用了以下

public class Point
{
    [Required]
    public double X { get; set; }
    [Required]
    public double Y { get; set; }
}

模型包含:

public List<Point> Vertices { get; set; }

但EF尝试根据此消息创建一个单独的表:

  

EntityType&#39; Point&#39;没有定义键。定义此EntityType的密钥。

我会为相关模型提供大量积分,我认为这不是拥有单独表格的最佳解决方案。 有没有办法在表格中嵌入点数组,或者我认为错了?

非常感谢您的时间。感谢。

1 个答案:

答案 0 :(得分:1)

以下情况应该有效 - 不确定我是否会推荐这种方法(因为我认为一个表格可以确定)但是说它确实对我有效。所以我使用VerticeDataText将点数据存储在一个字符串中,因此它存储在DB中:

public class Vertice
{
    public int VerticeID { get; set; }

    [NotMapped]
    public Point[] Data
    {
        get
        {
            string[] rawInternalData = this.VerticeDataText.Split(';');
            Point[] dataResult = new Point[rawInternalData.Length / 2];
            int count = 0;
            rawInternalData.ToList().ForEach(p =>
            {
                var pairArray = p.Split(',');
                dataResult[count++] = new Point { X = double.Parse(pairArray[0]), Y = double.Parse(pairArray[1])};
            });
            return dataResult;
        }
        set
        {
            StringBuilder sb = new StringBuilder();
            value.ToList().ForEach(p => sb.AppendFormat("{0},{1};", p.X, p.Y));
            this.VerticeDataText = sb.ToString();
        }
    }

    public string VerticeDataText { get; set; }
}