如何解决在第一次使用Entity Framework的代码期间,无法显式添加一对一的外键
好,所以我有两个表,Student
和Address
。我想要它们之间一对一的映射。
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; }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。