【问题标题】:Foreign Key that is defined in the hierachical Model在分层模型中定义的外键
【发布时间】:2013-01-07 15:21:50
【问题描述】:

在 EF5 中定义模型时遇到问题。我想将ParentId 作为数据库中的外键,但出现错误:

System.Data.Entity.Edm.EdmAssociationType: : 多重性与关系“Category_Parent”中角色“Category_Parent_Target”中的引用约束冲突。由于 Dependent Role 中的所有属性都不可为空,因此 Principal Role 的复数必须为“1”。

这是我的模型:

public class Category
{
    public Category()
    {
        this.Childs = new HashSet<Category>();
    }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Childs { get; set; } 
}

modelBuilder.Entity<Category>()
            .HasOptional(c => c.Parent)
            .WithMany(c => c.Childs)
            .HasForeignKey(d => d.ParentId);

【问题讨论】:

  • 请正确格式化您的代码...

标签: c# entity-framework


【解决方案1】:

如果Category 可能有也可能没有Parent,那么ParentId 可能有也可能没有值。

所以,让ParentId 可以为空:

public int? ParentId { get; set; }

【讨论】:

  • 我还有一个例外:序列不包含任何元素
  • 那是一个单独的问题。如果你在一个空集合上调用Single()First(),你会得到它。
猜你喜欢
  • 1970-01-01
  • 2018-01-03
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
相关资源
最近更新 更多