c# – 使用数据注释创建外键
发布时间:2020-12-15 08:45:04 所属栏目:百科 来源:网络整理
导读:在下面的代码中,我需要在ParentInfoAddProperties.ParentQuestionAnswersId上设置一个外键constrant,以便它依赖于ParentQuestionAnswers.Id(这是一个主键).我试图使用数据注释,但实体框架6想要在我的ParentQuestionAnswers表中创建一个新的外键列,该列引用Pa
在下面的代码中,我需要在ParentInfoAddProperties.ParentQuestionAnswersId上设置一个外键constrant,以便它依赖于ParentQuestionAnswers.Id(这是一个主键).我试图使用数据注释,但实体框架6想要在我的ParentQuestionAnswers表中创建一个新的外键列,该列引用ParentInfoAddProperties.Id列而不是ParentInfoAddProperties.ParentQuestionAnswersId列.我不希望Entity Framework创建新的外键列.
如果有人能够解释我应该指定哪些数据注释或(如果需要)流畅的映射来实现所需的外键实例,我将不胜感激.提前致谢. 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类下) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |