实体框架层次结构的代码优先映射
我有一个看起来像这样的模型:
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; }
}
有了一个看起来像这样的数据库表,
Categories
Id (PK varchar(5))
Description (nvarchar(50))
ParentId (FK varchar(5))
但在设置映射时我很困惑,
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?)。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么要在同一导航属性上映射多对多关系?这是完全错误的。首先,您的表显然期望一对多关系。即使您需要多对多关系,您也不能使用相同的导航属性。
试试:
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: