实体框架 4 CTP 5 自引用多对多

发布于 2024-10-17 07:03:07 字数 5897 浏览 3 评论 0原文

我的数据库中有以下场景。它是研究的记录,这些研究以其他研究为先决条件。在我的数据库设计中,它看起来像这样:

self 引用多对多

这样:

public class Study
{
    public int ID { get; set; }
    public string Topic { get; set; }
    public byte TypeID { get; set; }
    public virtual StudyType Type { get; set; }
    public bool Deprecated { get; set; }

    public virtual ICollection<Study> Prerequisites { get; set; }
}

public class StudyType
{
    public byte ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Study> Studies { get; set; }
}

public class MyContext : DbContext
{

    public DbSet<Study> Studies { get; set; }
    public DbSet<StudyType> StudyTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Study>()
            .HasMany(p=>p.Prerequisites)
            .WithMany().Map(ps =>
                {
                    ps.ToTable("Prerequisites");
                    ps.MapLeftKey(x=>x.ID,"StudyID");
                    ps.MapRightKey(y=>y.ID,"PrerequisiteID");
                });
    }

我的代码看起来像 不太擅长 EF 语法,但从我在 Google 上发现的内容来看,这似乎应该可行。相反,我得到序列包含多个匹配元素

我发现了这一点,但由于该实体正在引用自身,因此我无法仅在其中一个表中精确重命名关键字段: http://social.msdn.microsoft.com/Forums/eu/adonetefx/thread/745a2c4f-cb66-41ad-9524-15aa198c40c7

有人帮我解决这个问题吗?

编辑

以下是该异常的完整堆栈跟踪:

它在 LINQ 行上执行:var x = from s in db.Studies select s;

Server stack trace: 
 at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
 at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
 at System.Lazy`1.CreateValue()

Exception rethrown at [0]: 
 at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
 at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
 at System.Lazy`1.CreateValue()
 at System.Lazy`1.LazyInitValue()
 at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
 at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
 at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
 at System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider()
 at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
 at DataAccess.Sql.SqlStudyRepository.GetAll() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\DataAccess\Sql\SqlStudyRepository.cs:line 22
 at API.Controllers.StudiesController.Index() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\API\Controllers\StudiesController.cs:line 24
 at lambda_method(Closure , ControllerBase , Object[] )
 at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
 at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
 at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
 at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

I have the following scenario in my database. It is a record of Studies and those studies have other studies as prerequisites. In my DB design, it looks like this:

self referencing many to many

And my code looks something like this:

public class Study
{
    public int ID { get; set; }
    public string Topic { get; set; }
    public byte TypeID { get; set; }
    public virtual StudyType Type { get; set; }
    public bool Deprecated { get; set; }

    public virtual ICollection<Study> Prerequisites { get; set; }
}

public class StudyType
{
    public byte ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Study> Studies { get; set; }
}

public class MyContext : DbContext
{

    public DbSet<Study> Studies { get; set; }
    public DbSet<StudyType> StudyTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Study>()
            .HasMany(p=>p.Prerequisites)
            .WithMany().Map(ps =>
                {
                    ps.ToTable("Prerequisites");
                    ps.MapLeftKey(x=>x.ID,"StudyID");
                    ps.MapRightKey(y=>y.ID,"PrerequisiteID");
                });
    }

I'm not super good at the EF syntax, but from what I've found Googling, that seems like it should work. Instead, I get Sequence contains more than one matching element.

I found this, but since the entity is referencing itself, I can't exactly rename the key field in only one of the tables: http://social.msdn.microsoft.com/Forums/eu/adonetefx/thread/745a2c4f-cb66-41ad-9524-15aa198c40c7

Anybody help me through this?

EDIT

Here is the full stack trace of the exception:

It executes on a line of LINQ: var x = from s in db.Studies select s;

Server stack trace: 
 at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
 at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
 at System.Lazy`1.CreateValue()

Exception rethrown at [0]: 
 at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
 at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
 at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
 at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
 at System.Lazy`1.CreateValue()
 at System.Lazy`1.LazyInitValue()
 at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
 at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
 at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
 at System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider()
 at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
 at DataAccess.Sql.SqlStudyRepository.GetAll() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\DataAccess\Sql\SqlStudyRepository.cs:line 22
 at API.Controllers.StudiesController.Index() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\API\Controllers\StudiesController.cs:line 24
 at lambda_method(Closure , ControllerBase , Object[] )
 at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
 at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
 at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
 at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2024-10-24 07:03:07

这就是我在 EntityTypeConfiguration<> 中所拥有的内容CTP5中类似情况的实现。

HasMany(g => g.SubGroups)
    .WithMany(g => g.ParentGroups)
    .Map(m => m.ToTable("Groups_SubGroups"));

不确定这如何转化为直接配置 DbContext,但我想它应该很接近。

如果没记错的话,CTP5 中并不存在 LeftKey() RightKey() 语法,因此您只需使用它创建或期望的默认列名称。就我而言,它是 GroupId 和 GroupId1。遵循模式Id 和Id1,而不是。顺便说一下,还有1。

您遇到的错误确实看起来很熟悉,而且我不记得解决方案在任何方面都是显而易见的。但是,我不久前确实把这一切都设置好了,所以我对如何实现有效的东西的记忆有点瑞士奶酪。希望它能帮助一些人。

This is what I have in an EntityTypeConfiguration<> implementation for a similar situation in CTP5.

HasMany(g => g.SubGroups)
    .WithMany(g => g.ParentGroups)
    .Map(m => m.ToTable("Groups_SubGroups"));

Not sure exactly how that translates to configuring the DbContext directly, but I imagine it should be close.

If memory serves, LeftKey() RightKey() syntax wasn't quite there in CTP5, so you just have to use the default column names that it creates or is expecting. In my case, it is GroupId and GroupId1. That follows the pattern <class>Id and <class>Id1, not <field> and <field>1 by the way.

The error that you're getting does seem familiar and I don't remember that the solution was obvious in any way. But, I did set this all up a while ago so the memories of how I arrived at something that works is a bit swiss cheesed. Hope it helps some.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文