实体框架4.1树映射

时间:2011-05-21 19:18:02

标签: asp.net entity-framework mapping entity-framework-4.1

我将经典数据库树映射到实体框架实体时遇到问题。

这是我的db:

CREATE TABLE intranet_organization_units
(
 [OrganizationUnitId] INT IDENTITY PRIMARY KEY,
 [ParentOrganizationUnitId] INT NULL,
 [Name] NVARCHAR(50) NOT NULL
)

实体:

public class OrganizationUnit
{
    public int OrganizationUnitId { get; set; }
    public string Name { get; set; }
    public int? ParentOrganizationUnitId { get; set; }

    public virtual OrganizationUnit ParentOrganizationUnit { get; set; }
    public virtual ICollection<OrganizationUnit> ChildrenUnits { get; set; } 
}

最后映射:

   public class OrganizationUnitMapper : EntityTypeConfiguration<OrganizationUnit>
    {
        public OrganizationUnitMapper()
        {
            ToTable("intranet_organization_units");
            Property(x => x.Name).HasColumnName("Name").IsRequired();


            HasMany(x => x.ChildrenUnits).WithOptional().HasForeignKey(x => x.OrganizationUnitId);
            HasOptional(x => x.ParentOrganizationUnit).WithMany().HasForeignKey(x => x.ParentOrganizationUnitId);

        }
    }

当我运行应用程序时,我得到了这个例外:

在模型生成期间检测到一个或多个验证错误:

  

System.Data.Edm.EdmAssociationEnd ::   多重性在角色中无效   'OrganizationUnit_ChildrenUnits_Target'   谈恋爱   'OrganizationUnit_ChildrenUnits'。   因为依赖角色是指   关键属性,上界   依赖角色的多样性   必须是 1 。

那么问题出在哪里?谢谢

1 个答案:

答案 0 :(得分:4)

使用此:

public class OrganizationUnitMapper : EntityTypeConfiguration<OrganizationUnit>
{
    public OrganizationUnitMapper()
    {
        ToTable("intranet_organization_units");
        Property(x => x.Name).HasColumnName("Name").IsRequired();

        this.HasOptional(x => x.ParentOrganizationUnit)
            .WithMany(y => y.ChildrenUnits)
            .HasForeignKey(x => x.ParentOrganizationUnitId);
    }
}

定义此关联映射时,请说:

  • 组织单位具有可选父级
  • 父母可以有多个孩子
  • 儿童使用外键属性