嵌套实体集合

时间:2019-02-21 18:23:00

标签: entity-framework entity-framework-core ef-core-2.2

我有一种情况,我试图为特定目的使用同类型嵌套集合的可扩展层次结构,并且我使用的是 EF Core 2.2

public class Group:Entity
{
    public Group(Guid id):base(id)
    {
    }
   ...
   public List<Group> SubGroups { get; set; }
}

public abstract class Entity
{
   protected Entity(Guid id)
    {
        Id = id;
    }

    public Guid Id { get; private set; }
}

目标是保存如下数据:

|-GrandParent Group
   -Parent Group
   |--Child1 Group
      ---GrandChild1 Group
   |--Child2 Group
       ---GrandChild2 Group

错误

{System.InvalidOperationException: No suitable constructor found for entity type 'Group'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'guid' in 'Group(Guid guid)'.
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConstructorBindingConvention.Apply(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)

能否让我知道我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

该问题与嵌套集合无关,但与实体构造函数无关,并且不会与问题中的示例重现。

但是异常消息

  

找不到适用于实体类型“ Group”的合适的构造函数。以下构造函数具有无法绑定到实体类型属性的参数:无法绑定“ Group(Guid guid )”中的“ guid ”。

表示您已经在真实代码中使用过

public Group(Guid guid):base(guid)

问题是参数guid(而不是id)的名称。如Entity types with constructors中所述(在一些注意事项内):

  

参数类型和名称必须与属性类型和名称匹配,除了可以将属性用驼峰式大小写的情况用Pascal大小写。

在这种情况下,该属性称为Id,因此该参数必须与帖子中一样称为id

相关问题