I have the following poco class:
public class Category : IDisplayName
{
private ICollection<Category> children;
private Category parent;
public Category()
{
children = new List<Category>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Parent
{
get { return parent; }
set
{
parent = value;
}
}
public virtual ICollection<Category> Children
{
get { return children; }
set { children = value; }
}
}
This is a mapping file (I'm not sure if this is correct .. but I have no ideas, and there are all the documentation files there ...)
public class CategoryEntityConfiguration : EntityConfiguration<Category>
{
public CategoryEntityConfiguration()
{
Property(x => x.Name).IsRequired();
HasMany(x => x.Children).WithOptional(x => x.Parent);
HasOptional(x => x.Parent).WithMany(x => x.Children);
}
}
Pay attention to the "Parent" property and how I do not add them using the "Children" collection.
var cat_0 = new Category { Name = "Root" };
var cat_1 = new Category { Name = "Property", Parent = cat_0 };
var cat_2 = new Category { Name = "Property Services", Parent = cat_1 };
var cat_3 = new Category { Name = "Housing Association", Parent = cat_2 };
var cat_4 = new Category { Name = "Mortgages & Conveyancing", Parent = cat_2 };
var cat_5 = new Category { Name = "Property Management", Parent = cat_2 };
var cat_6 = new Category { Name = "Property Auctions", Parent = cat_2 };
var cat_7 = new Category { Name = "Landlords Wanted", Parent = cat_2 };
context.Set<Category>().Add(cat_0);
When I save cat_0 in the database, only 1 row is inserted, and the Entity Framework does not receive the fact that cat_0 is the parent of a whole group of other objects and does not understand that they must be saved. I have a workaround that is commented out code in a property of the Parent category. But I would rather not do this, as it is not.
Any help would be greatly appreciated
Jake