我已经查看了围绕SO上此异常的现有问题,但似乎都不适用于我的情况。
引用约束中的依赖属性映射到存储生成的列。列:"架构字典 ID"。
在包管理器控制台中执行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
}
Schema
和SchemaDictionary
之间的关系应该是从一到零或一...
-
Schema
对象将有零个或一个SchemaDictionary
-
SchemaDictionary
将始终有一个Schema
.
我对这个问题的理解是,它无法维护 FK 约束,因为 EF 不知道外键GUID
。当定义了这样的依赖关系时,如何插入种子数据?
当你这样做时:
modelBuilder.Entity<SchemaDictionary>()
.HasRequired(sd => sd.Schema)
.WithOptional(s => s.SchemaDictionary);
您正在配置必需到可选的关系(一对一到零或一)。您指定SchemaDictionary
是从属的,Schema
是主体的
在实体框架中具有一对一关系时,依赖项中的 PK 也必须是主体的 FK。但是您已指定它应该是数据库生成的。该列不能同时是 FK 和 IDENTITY,因此您会收到错误消息。应从SchemaDictionaryId
属性中删除HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
除此之外,您的某些代码是不必要的
HasKey
因为 EF 将假定SchemaId
和SchemaDictionaryID
是命名约定的键对不可为空的字段
IsRequired()
引用:
映射时,哪个是 end 是主体?
主体结束是什么意思?