There are several questions on this topic, but my question is very specific for true self-reference. All examples for other questions are circular links, and this does not help me in this case.
Let's say I have this model:
public class User { [Key] public int Id { get; set; } ... public int CreatedByUserId { get; set; } }
and this mapping:
public class UserMap : EntityTypeConfiguration<User> { public UserMap() { this.HasRequired(a => a.CreatedByUser) .WithMany() .HasForeignKey(u => u.CreatedByUserId); } }
After the migration, a database with this code is created, I can manually add the user to SQL Management Studio with the identifier Id = 1 and CreatedByUserId = 1 so that he tells me that such links can work.
However, when using EF to create a user, I run into the problem of "unable to determine the valid order for dependent operations." There are many questions on this subject that include a new object that refers to another new object that has a foreign key for the first object, which is a circular reference. The solution in these cases either saves one of the entities first, or has an identifier with a zero value for the foreign key of the circular entity. I can not do any of them, because the first would be impossible, and the second - an external restriction, that I can not have identifiers with zero values.
So, seeing how I can achieve this by adding a manual entry, I can assume that this is an EF5 limitation. What work around?
c # sql entity-framework
Levitikon
source share