对于代码优先方法,我有以下几类。我明确声明要让StudentId列成为表Addresses中的外键。
public class Student
{
[ForeignKey("Address")]
public int StudentId { get; set;}
public string StudentName { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string AddressName { get; set; }
public virtual Student Student { get; set; }
}
运行迁移时,这是刷新后在SQL Server中看到的内容,学生表中没有外键列。
我该怎么办,原因是什么?
答案 0 :(得分:1)
ForeignKey属性被分配给StudentId属性。这样会在“学生”表中的“ StudentId”列(也是主键)和“地址”表中的“ AddressId”列之间生成外键关系。
假设您需要一个明确的外键,则应在您的Student类中添加一个AddressId列,并使用ForeignKey属性指定它,如下所示:
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Address Address { get; set; }
[ForeignKey("Address")]
public int AddressId { get; set; }
}
答案 1 :(得分:1)
当前StudentId
(PK)用作引用AddressId
(PK)的外键(由于对其应用了ForeignKey
属性)
如下所示:
如果您希望Student
表具有一个名为AddressId
的附加列(FK)并引用AddressId
(Address
表PK),请遵循以下实现需要额外的ForeignKey
属性,因为当EF的名称与相关实体的主键属性匹配时,EF会将其作为外键属性)
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string AddressName { get; set; }
public virtual Student Student { get; set; }
}
结果如下: