EF迁移异常:ReferentialConstraint中的依赖属性映射到存储生成的列

时间:2013-11-05 16:13:56

标签: c# entity-framework asp.net-mvc-4 ef-migrations

我在SO上查看了有关此例外的现有问题,但似乎没有一个适用于我的情况。

  

ReferentialConstraint中的依赖属性映射到存储生成的列。专栏:'SchemaDictionaryId'。

我在程序包管理器控制台中执行Update-Database时收到此异常。

我的种子方法如下:

protected override void Seed(DataEntry.App_Data.DataEntryDataContext context)
{
    context.Schemas.AddOrUpdate(s => s.SchemaId, _generateSchemaData());
    context.SaveChanges();
}

private Schema[] _generateSchemaData()
{
    List<Schema> schemas = new List<Schema>();
    // Loop removed for simplicity
    schemas.Add(new Schema
    {
        // various property assignments
        SchemaDictionary = new SchemaDictionary
        {
            // various property assignments
        }
    });
    return schemas.ToArray();
}

我的DbContext子类包含以下流畅的API定义(为相关性而修剪):

modelBuilder.Entity<Schema>()
    .HasKey(s => s.SchemaId);

modelBuilder.Entity<Schema>()
    .Property(s => s.SchemaId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
    .IsRequired();

modelBuilder.Entity<SchemaDictionary>()
    .HasKey(sd => sd.SchemaDictionaryId);

modelBuilder.Entity<SchemaDictionary>()
    .Property(s => s.SchemaDictionaryId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
    .IsRequired();

modelBuilder.Entity<SchemaDictionary>()
    .HasRequired(sd => sd.Schema)
    .WithOptional(s => s.SchemaDictionary);

最后有问题的POCO:

public class Schema
{
    public Guid SchemaId { get; set; }

    public Nullable<Guid> SchemaDictionaryId { get; set; }
    public virtual SchemaDictionary SchemaDictionary { get; set; }

    // various other properties
}

public class SchemaDictionary
{
    public Guid SchemaDictionaryId { get; set; }

    public Nullable<Guid> SchemaId { get; set; }
    public virtual Schema Schema { get; set; }

   // various other properties
}

SchemaSchemaDictionary之间的关系应为一到零或一类型...

  • Schema对象将有零个或一个SchemaDictionary
  • SchemaDictionary将始终只有一个Schema

我对该问题的理解是它不能支持FK约束,因为EF不知道GUID外键。如果定义了这种依赖关系,如何插入种子数据?

1 个答案:

答案 0 :(得分:8)

执行此操作时:

modelBuilder.Entity<SchemaDictionary>()
    .HasRequired(sd => sd.Schema)
    .WithOptional(s => s.SchemaDictionary);

你是Configuring a Required-to-Optional Relationship (One-to–Zero-or-One)。您指定SchemaDictionary是依赖项,Schema是主体

当您在Entity Framework中具有一对一关系时,依赖关系中的PK也必须是主体的FK。但是您已指定它应该是数据库生成的。该列不能同时是FK和IDENTITY,因此您会收到错误消息。您应该从HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)属性

中删除SchemaDictionaryId

除此之外,您的一些代码是不必要的

  1. HasKey因为EF会假定SchemaIdSchemaDictionaryID是命名惯例的关键

  2. IsRequired()关于不可空的字段

  3. 参考文献:

    When mapping, which is end is the principal?

    What does principal end mean?