在第一次使用Entity Framework的代码期间,无法显式添加一对一的外键

问题描述

好,所以我有两个表,StudentAddress。我想要它们之间一对一的映射。

    public class Student
    {
        public int StudentId { get; set;}
        public string StudentName { get; set; }
        public Address StudentAddress { get; set; }
    }

    public class Address
    {
        public int AddressId { get; set; }
        public string AddressName { get; set; }
        
        public int StudentId { get; set; }
        [ForeignKey("StudentId")]
        public Student Student;
    }

以前,我一直很简单,我没有使用ForeignKey属性,而是将Address对象放在Student类中,并且Entity Framework完成了它的工作。它在AddressId表中添加了名为Student的列。

问题是,我希望StudentId作为外键进入Address表,而不是相反。当前,Entity Framework正在Student表中生成存储AddressId的外键。我不要这个。

我想知道在使用代码优先方法将一对一关系映射到Entity Framework中时如何明确定义包含外键的表吗?

谢谢。

解决方法

尝试将您的课程更改为:

public class Student
{
    public int StudentId { get; set;}
    public string StudentName { get; set; }
    public virtual Address StudentAddress { get; set; }
}

public class Address
{
    [Key,ForeignKey("Student")]
    public int AddressId { get; set; }
    public string AddressName { get; set; }       
    public virtual Student Student;
}

这是因为一对一关系的关键是相同的

,
public class Student
    {
        public int StudentId { get; set;}
        public string StudentName { get; set; }      
        public int StudentId { get; set; }
        [ForeignKey("StudentId ")]
        public virtual Student Student { get; set; }
    }
    public class Address
    {
        public int AddressId { get; set; }
        public string AddressName { get; set; }      
        public int AddressId { get; set; }
        [ForeignKey("AddressId")]
        public virtual Address Address { get; set; }
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...