【发布时间】:2014-05-21 11:10:59
【问题描述】:
我有以下实体:
public class Category
{
public virtual long Id { get; set; }
public string Name { get; set; }
public virtual long ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual List<Category> Categories { get; set; }
}
public class CategoryConfiguration:
EntityTypeConfiguration<Category>
{
public CategoryConfiguration ()
{
this.HasKey(entity => entity.Id);
this.Property(entity => entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasRequired(entity => entity.Parent).WithMany(entity => entity.Categories).HasForeignKey(entity => entity.ParentId);
this.HasMany(entity => entity.Categories).WithRequired(entity => entity.Parent).HasForeignKey(entity => entity.ParentId);
this.Property(entity => entity.Name).IsRequired().HasMaxLength(1000);
}
}
EF 能够很好地创建架构,但在使用以下代码插入数据时出现问题:
var category = new Category();
category.Name = "1";
category.Description = "1";
category.Parent = category;
using (var context = new Context())
{
context.Categories.Add(category);
context.SaveChanges();
}
错误:Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
我猜这是因为ParentId 字段是non-nullable(这是意图)。如果不使用 ORM,我通常会:
- 将列类型设置为
nullable。 - 创建一个主类别以自动生成主键。
- 将
ParentId设置为新生成的主键。 - 再次将列类型设置为
non-nullable。
如何使用 EntityFramework 实现这一点?
【问题讨论】:
-
我不认为你可以在引用自身的 sql 表中插入一行,并且引用不可为空,这是这里的主要问题。
标签: c# .net entity-framework circular-reference self-reference