问题描述
在下面的代码中,我需要在ParentInfoAddProperties.ParentQuestionAnswersId上设置一个外键constrant,以便它依赖于ParentQuestionAnswers.Id(这是一个主键)。我试图使用数据注释,但实体框架6想在我的ParentQuestionAnswers表中创建一个新的外键列,它引用了ParentInfoAddProperties.Id列而不是ParentInfoAddProperties.ParentQuestionAnswersId列。我不希望实体框架创建一个新的外键列。
In the code below, I need to set a foreign key constrant on ParentInfoAddProperties.ParentQuestionAnswersId so that it is dependent on ParentQuestionAnswers.Id (which is a Primary Key). I am attempting to do so using data annotations but Entity Framework 6 wants to create a new Foreign Key column in my ParentQuestionAnswers table which references the ParentInfoAddProperties.Id column not the ParentInfoAddProperties.ParentQuestionAnswersId column. I do not want Entity Framework to create a new foreign key column.
如果有人可以解释什么数据注释或(如有必要)流畅的映射,我应该非常感谢指定实现期望的外键驻留。感谢提前。
I'd greatly appreciate if someone can explain what data annotations or (if necessary) fluent mappings I should specify to achieve the desired foreign key constrant. Thanks in advance.
namespace Project.Domain.Entities
{
public class ParentQuestionAnswers
{
public ParentQuestionAnswers()
{
ParentInfoAddProperties = new ParentInfoAddProperties();
}
[Required]
public int Id { get; set; }
[Required]
public int UserId { get; set; }
public ParentInfoAddProperties ParentInfoAddProperties { get; set; }
}
public class ParentInfoAddProperties
{
[Required]
public int Id { get; set; }
[Required]
public int ParentQuestionAnswersId { get; set; }
}
}
推荐答案
您可以使用以下数据注释,并使用实体代替int
You could use the following data annotation, and use entity instead of int
[Required]
[ForeignKey("ParentQuestionAnswers")]
public ParentQuestionAnswers ParentQuestionAnswers { get; set; }
获取ID只能添加属性
public int ParentQuestionAnswersId { get; set; }
但您仍然需要 ParentQuestionAnswers
属性所以EF会明白你的意思
but you still need the ParentQuestionAnswers
property so EF will understand you .
(这些代码行应位于 ParentInfoAddProperties
类)
(these code rows should be under the ParentInfoAddProperties
class)
这篇关于使用数据注释创建外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!