实体框架层次结构的代码优先映射 [英] Code First Mapping for Entity Framework Hierarchy

查看:148
本文介绍了实体框架层次结构的代码优先映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的模型:

  public class Category 
{
public string Id {get;组; }
public string描述{get;组; }
public Category Parent {get;组; }
public ICollection< Category>孩子{get;组; }
public ICollection< Product>产品{get;组;
}

一个数据库表看起来像

 类别
Id(PK varchar(5))
描述(nvarchar(50))
ParentId(FK varchar ))

但是,在设置映射时,Im被拒绝

  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);
});

我可以看到为什么映射失败(StackOverflowException),但不确定如何解决它。任何帮助都会非常感激。



这是使用最新版本的EF(4.1?)。



谢谢!

解决方案

为什么在相同的导航属性上映射多对多关系?这是完全错误的。首先,你的表格显然期待一对多关系。即使您需要多对多关系,您也不能使用相同的导航属性。



只需尝试:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $
.Map(m => m.MapKey(ParentId));


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

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"));

这篇关于实体框架层次结构的代码优先映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆