我正在尝试在实体框架5代码中首先创建一个简单的自引用。一个项目可以有一个可选的子项,不需要知道它的父项。
public class Item
{
public int ItemId { get; set; }
public int? PreviousItemId { get; set; }
public virtual Item PreviousItem { get; set; }
}
但是由于某些原因它不想使用我的关键字段,因为我最终得到了这三个:
ItemId
PreviousItemId
PreviousItem_ItemId
我希望它使用我指定的字段而不是最后一个字段。我试过一个注释:
[ForeignKey("PreviousItemId")]
public virtual Item PreviousItem { get; set; }
还有流利的api:
public class ItemConfiguration : EntityTypeConfiguration<Item>
{
public ItemConfiguration()
{
HasOptional(i => i.PreviousItem)
.WithMany()
.HasForeignKey(i => i.PreviousItemId);
}
}
但我同时收到这两个例外:
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.GetQualifiedTableName(XDocument model, String entitySetName)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<FindRenamedIndependentAssociationColumns>b__ba(<>f__AnonymousType16`2 <>h__TransparentIdentifieraa)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, String connectionString)
at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Sequence contains no elements
谁能告诉我这里我做错了什么?谢谢阅读。当我从包管理器控制台运行update-database时会发生异常。