使用数据注释创建外键

编程入门 行业动态 更新时间:2024-10-26 18:25:38
本文介绍了使用数据注释创建外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的代码中,我需要在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)

更多推荐

使用数据注释创建外键

本文发布于:2023-10-14 21:39:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!