简体   繁体   English

实体框架映射ID列表

[英]Entity Framework mapping list of ids

I am in a strange situation right now, I have two entities: 我现在处于一种奇怪的情况,我有两个实体:

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

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

I know that this is not the best way to model this kind of relation (n->1) but it was done this way and we can't change it. 我知道这不是对这种关系进行建模的最佳方法(n-> 1),但是这种方式已经完成,我们无法更改。

Does someone know, how do I relate this entities (notation or overriding onModelCreation )? 有人知道吗,我如何关联这个实体(符号或覆盖onModelCreation )?

We are using c#, ET4, VS2012, WS8. 我们正在使用c#,ET4,VS2012,WS8。

I like to use Data Annotations for simple relationships. 我喜欢将数据注释用于简单的关系。 You must specify your key field on the Proyect table, and your foreign key on the Stage table. 您必须在Proyect表上指定键字段,并在Stage表上指定外键。 In the Proyect table, you should have a list of Stages, not ints, since you are relating to the Stage object. 在Proyect表中,应该有一个Stage列表,而不是ints列表,因为您与Stage对象有关。 You can use the virtual keyword to use lazyloading on your related entities. 您可以使用virtual关键字在相关实体上使用lazyloading

If you really need a list of type int, containing your stage Ids, just use an unmapped property. 如果确实需要包含舞台ID的int类型列表,则只需使用未映射的属性即可。

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;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM