我有ApplicationForm类来存储申请该网站的用户信息。 ApplicationFormAnswer用于在每个申请表中存储自定义字段答案。
public class ApplicationFormAnswer
{
public Guid Id { get; set; }
public string FieldId { get; set; }
public ApplicationCustomFieldType FieldType { get; set; }
public string Name { get; set; }
public string Answer { get; set; }
public virtual ApplicationForm ApplicationForm { get; set; }
public Guid ApplicationFormId { get; set; }
}
和在ApplicationForm类中
public class ApplicationForm
{
public Guid Id { get; set; }
.....
....
public virtual ICollection<ApplicationFormAnswer> ApplicationFormAnswers { get; set; }
}
当我尝试进行迁移时,它给了我这个错误:
在引用表'dbo.ApplicationForms'中没有与外键'FK_dbo.ApplicationFormAnswers_dbo.ApplicationForms_ApplicationFormId'中的引用列列表匹配的主键或候选键。 无法创建约束或索引。查看以前的错误。
编辑:
当我应用-verbose时,我看到创建了SQL查询:
CREATE TABLE [dbo].[ApplicationFormAnswers] (
[ApplicationFormId] [uniqueidentifier] NOT NULL,
[Id] [uniqueidentifier] NOT NULL,
[FieldId] [nvarchar](max),
[FieldType] [int] NOT NULL,
[Name] [nvarchar](max),
[Answer] [nvarchar](max),
[ApplicationFormCustomField_FieldId] [nvarchar](max),
[ApplicationFormCustomField_Order] [int] NOT NULL,
[ApplicationFormCustomField_Name] [nvarchar](max),
[ApplicationFormCustomField_FieldType] [int] NOT NULL,
[ApplicationFormCustomField_IsRequired] [bit] NOT NULL,
[ApplicationFormCustomField_IsIncluded] [bit] NOT NULL,
[ApplicationFormCustomField_CanBeDeleted] [bit] NOT NULL,
[ApplicationFormCustomField_IsDeleted] [bit] NOT NULL,
CONSTRAINT [PK_dbo.ApplicationFormAnswers] PRIMARY KEY ([ApplicationFormId])
)
CREATE INDEX [IX_Id] ON [dbo].[ApplicationFormAnswers]([Id])
ALTER TABLE [dbo].[ApplicationFormAnswers] ADD CONSTRAINT [FK_dbo.ApplicationFormAnswers_dbo.ApplicationForms_Id] FOREIGN KEY ([Id]) REFERENCES [dbo].[ApplicationForms] ([Id]) ON DELETE CASCADE
我看到它使ApplicationFormId成为主键,但主键应为ID。我试图将[Key]放在ID上方,但仍然无法正常工作。
答案 0 :(得分:0)
我认为问题在于,您将[ApplicationFormId]
设置为唯一标识符时,只是一个FK。
只需将int
中的ApplicationFormAnswers
输入[ApplicationFormId]
答案 1 :(得分:0)
由于您的Id
属性是GUID而不是int
,因此EF不会自动将其识别为ID。您可以使用[KeyAttribute]
或流利的API手动配置ID:
public class ApplicationFormAnswer
{
[Key]
public Guid Id { get; set; }
//...
}
public class ApplicationForm
{
[Key]
public Guid Id { get; set; }
//...
}
...或...
modelBuilder.Entity<ApplicationFormAnswer>().HasKey(e => e.Id);
您还应该手动配置外键:
public class ApplicationFormAnswer
{
[Key]
public Guid Id { get; set; }
public Guid ApplicationFormId { get; set; }
[ForeignKey("ApplicationFormId")]
public virtual ApplicationForm ApplicationForm { get; set; }
//...
}
...或...
modelBuilder.Entity<ApplicationFormAnswer>()
.HasOne(e => e.ApplicationForm)
.WithMany(e => e.ApplicationFormAnswers)
.HasForeignKey(e => e.ApplicationFormId);