实体框架映射ID列表

时间:2015-11-19 14:58:08

标签: c# entity-framework

我现在处于一种奇怪的境地,我有两个实体:

public class Proyect
{
    int id;
    List<int> stages;
}

public class Stage
{
    //PK, not FK to proyect
    int id;
}

我知道这不是模拟这种关系的最好方法(n-> 1) 但是这样做了,我们无法改变它。

有人知道,我如何关联这些实体(符号或覆盖onModelCreation)?

我们正在使用c#,ET4,VS2012,WS8。

1 个答案:

答案 0 :(得分:2)

我喜欢将数据注释用于简单的关系。您必须在Proyect表上指定密钥字段,并在Stage表上指定外键。在Proyect表中,您应该有一个阶段列表,而不是整数,因为您与Stage对象有关。您可以使用virtual关键字在相关实体上使用lazyloading

如果你真的需要一个int类型的列表,包含你的阶段ID,只需使用一个未映射的属性。

public class Proyect{
    [Key]
    public int id { get; set;}
    public virtual List<Stage> stages { get; set;}
    [NotMapped]
    public virtual List<int> stageIds {
        get {
            return stages == null ? null : stages.Select(t => t.id).ToList();
        }
    }
}

public class Stage{
    public int id { get; set;}
    [ForeignKey("id")]
    public virtual Proyect Proyect { get; set;}
}
相关问题