-
20-12-2019 - |
题
在下面的代码中,我需要在parentinfoaddproperties上设置外键约束.ParentQuestionAnswersID,以便它依赖于ParentQuestionAnswers.id(这是一个主要键)。我尝试使用数据注释这样做,但实体框架6想要在我的parentQuestionanswers表中创建一个新的外键列,该表引用parentinfoaddproperties.id列而不是parentinfoaddproperties.parentquestionanswersid列。我不希望实体框架创建一个新的外键列。
我非常欣赏,如果有人可以解释什么数据注释或(如有必要)流利的映射,我应该指定达到所需的外国密钥约束。提前致谢。
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
[Required]
[ForeignKey("ParentQuestionAnswers")]
public ParentQuestionAnswers ParentQuestionAnswers { get; set; }
.
只能获取ID,只能添加属性
public int ParentQuestionAnswersId { get; set; }
.
但你仍然需要ParentQuestionAnswers
属性,因此EF将理解您。
(这些代码行应该在ParentInfoAddProperties
类下)
其他提示
添加
[KeyAttribute]
.
到ID列
和
[ForeignKeyAttribute]
.
到parentquestionanswersid属性。
不隶属于 StackOverflow