locked
One to many relation and how EF understand which column will be fk in details table RRS feed

  • Question

  • User828542847 posted

    see the code and taken from https://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/10/21/how-to-create-relationships-between-entities-in-the-entity-framework-code-first-approach.aspx

    public class Student
    {
    	public Student()
    	{
    	   StudentAddresses = new HashSet<StudentAddress>();
    	}
    
    	public int Id { get; set; }
    	public string Name { get; set; }
    	public int Age { get; set; }
    	public ICollection<StudentAddress> StudentAddresses { get; set; }
    }
        
    public class StudentAddress
    {
        public int Id { get; set; }
        public string  Address { get; set;}
        public int StudentId { get; set; }
        public virtual Student Student { get; set; }
    }
    

    when i migrate then i saw StudentId become FK in StudentAddress table. so my question is how EF can understand that StudentId has to be fk. just by naming convention ?

    if yes then if i change the name from StudentId to stdfkid then how i can instruct EF to make this field fk?

    Thursday, July 20, 2017 1:23 PM

Answers

  • User828542847 posted

    after reading some data i understand EF understand what field will be PK and FK

    id field will be pk and reference table name with id named column will be fk in child table.

    we can give different name to fk field by foreign key attribute like

        public class Student
        {
            public Student()
            {
                StudentAddresses = new HashSet<StudentAddress>();
            }
    
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
            public ICollection<StudentAddress> StudentAddresses { get; set; }
        }
    
        public class StudentAddress
        {
            public int Id { get; set; }
            public string Address { get; set; }
            public int stdid { get; set; }
    
            [ForeignKey("stdid")]
            public virtual Student Student { get; set; }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 20, 2017 2:40 PM