0

我正在尝试首先在实体框架 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 时发生异常。

4

0 回答 0