Parent-Child Relationship in Fluent API
Okay, this is getting ridiculous as this is turning out to be much more difficult than it has any right to be.
If I use my original code with no FluentAPI mapping, I have a ParentID field which is not used, and a new field called Node_ID is used.
public class Node {
public long ID { get; private set; }
public long ParentID { get; set; }
public ICollection<Node> Children { get; set; }
}
Here are my various attempts:
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<Node>()
.HasMany<Node>(h => h.Children)
.WithOptional()
.HasForeignKey(h => h.ParentID);
}
DbUpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
protected override void OnModelCreating(DbM开发者_开发问答odelBuilder mb)
{
mb.Entity<Node>()
.HasMany<Node>(h => h.Children)
.WithOptional()
.Map(m => m.MapKey("ParentID"));
}
MetadataException: Schema specified is not valid. Errors: (82,6) : error 0019: Each property name in a type must be unique. Property name 'ParentID' was already defined.
[ForeignKey("ParentID")]
public ICollection<Node> Children { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<Node>()
.HasMany<Node>(h => h.Children)
.WithOptional()
}
DbUpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Update
Using the Fluent API code from my first attempt code above (.HasForeignKey), and by making ParentID nullable (public long? ParentID), I have gotten the database to successfully map. Is there any way to do this without making the FK nullable? I would like the key to be 0 when no parent exists. If not, oh well, I will deal.
No there is no way to avoid nullable ParentId
- you told EF that parent is optional (it must be otherwise you will not be able to use the table) and because of that related FK property must be nullable.
精彩评论