写一个私有属性,它是自己的类对象的列表

时间:2018-07-22 07:08:13

标签: c# entity-framework

我有一个具有一些私有属性的类,这些私有属性是其自己的类型的列表。当我想配置实体框架以在写入数据库时​​考虑它们时,出现此错误:

  

“ ICollection ”类型必须是不可为空的值类型,才能在通用类型或方法中将其用作参数“ T”

课程是:

public partial class ModelItem
{
    public int Id { get; set; }

    public string Lable { get; set; }

    private ICollection<ModelItem> Prop_InputNodes
    {
        get;  set;
    }

    public class ModelItemConfiguration : EntityTypeConfiguration<ModelItem>
    {
        public ModelItemConfiguration()
        {
            Property(x => x.Prop_InputNodes); // <<-- Error raises here
        }
    }
}

我几乎在stackoverflow中看到所有类似的帖子,但是我找不到解决方案。 您知道问题出在哪里吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您应该使用集合映射方法:

public class ModelItemConfiguration : EntityTypeConfiguration<ModelItem>
{
    public ModelItemConfiguration()
    {
        this.HasMany(x => x.Prop_InputNodes);
    }
}

这将创建根据默认约定命名的外键字段:ModelItem_Id。如果要更改名称,可以执行以下操作:

this.HasMany(x => x.Prop_InputNodes)
    .WithOptional()
    .Map(m => m.MapKey("ParentID"));
相关问题