2

I have this model:

public class ContentType
{
    public int ContentTypeId{get;set;}
    public string Name{get;set;}
    public Lang Lang{get;set;}
    public bool IsPublished{get;set;}
    public int? ParentId { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
    public virtual ContentType Parent { get; set; }
    public virtual List<ContentType> Children { get; set; }
}

It has a one to many relation to itself.

And in Context I have this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ContentType>().HasMany(c => c.Children).WithOptional(c => c.Parent).HasForeignKey(c => c.ParentId);
    base.OnModelCreating(modelBuilder);
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();    
}

But when I am saving a record with ParentId=0 I see this error:

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

Note that the relation in database is not exist because of the following error:

'ContentType' table - Unable to create relationship 'FK_ContentType_ContentType'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ContentType_ContentType". The conflict occurred in database "CMS", table "dbo.ContentType", column 'ContentTypeId'.

But I don't think the problem be from here.I don't know.

What is it wrong here?

Hamid Reza
  • 2,913
  • 9
  • 49
  • 76

1 Answers1

3

It seems that both errors are caused by the incorrect data in the table ContentType.

'ContentType' table - Unable to create relationship 'FK_ContentType_ContentType'. The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ContentType_ContentType". The conflict occurred in database "CMS", table "dbo.ContentType", column 'ContentTypeId'.

This points to the incorrect value in ParentId field. Verify that values in this field are in fact correct ContentTypeId in other records.

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

This error points to a circular dependency. Verify that you do not have cycles in your data.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • It is supposed that when a content type doesn't have a parent,the parentId field be 0. From your answer I think I should set the parent id for the root content types to null.right? – Hamid Reza Dec 24 '13 at 12:23
  • @HamidReza, absolutely. 0 is an integer, so DB treats it as a valid ID. Moreover your `ParentId` field is nullable, so I guess you where bearing the same design in mind when creating it. – Andrei Dec 24 '13 at 12:26