Create Foreign Key using Data Annotations

馋奶兔 提交于 2020-01-01 05:18:12

问题


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; }
    }
}

回答1:


You could use the following data annotation, and use entity instead of int

[Required]
[ForeignKey("ParentQuestionAnswers")]
public ParentQuestionAnswers ParentQuestionAnswers { get; set; }

to get the Id only you could add the property

public int ParentQuestionAnswersId { get; set; }

but you still need the ParentQuestionAnswers property so EF will understand you .

(these code rows should be under the ParentInfoAddProperties class)




回答2:


Add the

[KeyAttribute] 

to the Id column

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.keyattribute(v=vs.110).aspx

and

[ForeignKeyAttribute]

to the ParentQuestionAnswersId property.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.foreignkeyattribute.foreignkeyattribute(v=vs.110).aspx



来源:https://stackoverflow.com/questions/24000907/create-foreign-key-using-data-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!