开发者

Code First Mapping for Entity Framework Hierarchy

开发者 https://www.devze.com 2023-03-06 22:57 出处:网络
I have a model that looks like this: public class Category { public string Id { get; set; } public string Description { get; set; }

I have a model that looks like this:

public class Category
{
    public string Id { get; set; }
    public string Description { get; set; }
    public Category Parent { get; set; }
    public ICollection<Category> Children { get; set; }
    public ICollection<Product> Products { get; set; }
}

With a database table that looks like

开发者_如何学Go
Categories
    Id (PK varchar(5))
    Description (nvarchar(50))
    ParentId (FK varchar(5))

But Im stumped when it comes to setting up the mapping

modelBuilder.Entity<Category>()
    .HasMany(x => x.Children)
    .WithMany(x => x.Children)
    .Map(m =>
        {
            m.ToTable("Categories");
            m.MapLeftKey(x => x.Id, "Id");
            m.MapRightKey(x => x.Id, "ParentId");
        });

I can see why the mapping fails (StackOverflowException), but am unsure as to how to fix it. Any help would be greately appreciated.

This is using the latest release of EF (4.1?).

Thanks!


Why do you map many-to-many relation on the same navigation property? That is completely wrong. First your table obviously expect one-to-many relation. Even if you need many-to-many relation you cannot use the same navigation property for that.

Just try:

modelBuilder.Entity<Category>()
            .HasMany(x => x.Children)
            .WithOptional(y => y.Parent)
            .Map(m => m.MapKey("ParentId"));
0

精彩评论

暂无评论...
验证码 换一张
取 消