1

我有一个场景,我试图为特定目的创建一个相同类型的嵌套集合的可增长层次结构,并且我正在使用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)

你能告诉我我怎么能做到这一点吗?

4

1 回答 1

2

该问题与嵌套集合无关,而是与实体构造函数有关,并且未与问题中的示例一起复制。

但是异常消息

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

表示在你的真实代码中你使用过

public Group(Guid guid):base(guid)

问题是参数的名称guid(而不是id)。正如Entity types with constructors中所解释的(在Some things to note 中):

参数类型和名称必须与属性类型和名称匹配,除了属性可以是 Pascal 大小写,而参数是驼峰式大小写。

在这种情况下,该属性被调用Id,因此必须id像在帖子中那样调用参数。

于 2019-02-21T19:04:51.350 回答