C# 实体框架未在SQL Server中创建外键

C# 实体框架未在SQL Server中创建外键,c#,.net,entity-framework,entity-framework-6,ef-code-first,C#,.net,Entity Framework,Entity Framework 6,Ef Code First,对于代码优先方法,我有以下几个类。我明确声明我希望列StudentId是表地址中的外键 public class Student { [ForeignKey("Address")] public int StudentId { get; set;} public string StudentName { get; set; } public virtual Address Address { get; set; } } public clas

对于代码优先方法,我有以下几个类。我明确声明我希望列StudentId是表地址中的外键

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中看到的,学生表中没有外键列


我能做什么,原因是什么?

ForeignKey属性被分配给StudentId属性。这将在Students表中的StudentId列(也是主键)和Address表中的AddressId列之间生成外键关系

假设需要显式外键,则应向学生类添加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; }
}
现在,您应该可以在Students表中看到FK列

将ForeignKey属性指定给StudentId属性。这将在Students表中的StudentId列(也是主键)和Address表中的AddressId列之间生成外键关系

假设需要显式外键,则应向学生类添加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; }
}
现在,您应该可以在Students表中看到FK列

目前
StudentId
(PK)用作外键,指的是
地址ID
(PK)(由于
外键上应用了
属性)
如下所示:

如果您希望
Student
表中有一个名为
AddressId
的附加列(FK),引用
AddressId
Address
table PK),请遵循以下实现,不需要额外的
ForeignKey
属性,因为当属性的名称与相关实体的主键属性匹配时,EF将属性作为外键属性)

公共班级学生
{
公共int StudentId{get;set;}
公共字符串StudentName{get;set;}
public int AddressId{get;set;}
公共虚拟地址{get;set;}
}
公共课堂演讲
{
public int AddressId{get;set;}
公共字符串地址名{get;set;}
公共虚拟学生学生{get;set;}
}
导致以下结构:


目前
StudentId
(PK)用作外键,指的是
地址ID
(PK)(由于
外键上应用了
属性)
如下所示:

如果您希望
Student
表中有一个名为
AddressId
的附加列(FK),引用
AddressId
Address
table PK),请遵循以下实现,不需要额外的
ForeignKey
属性,因为当属性的名称与相关实体的主键属性匹配时,EF将属性作为外键属性)

公共班级学生
{
公共int StudentId{get;set;}
公共字符串StudentName{get;set;}
public int AddressId{get;set;}
公共虚拟地址{get;set;}
}
公共课堂演讲
{
public int AddressId{get;set;}
公共字符串地址名{get;set;}
公共虚拟学生学生{get;set;}
}
导致以下结构:


您的解决方案不起作用,您没有定义原则表和从属表。按照EF约定,无需进行修改。我不知道为什么它对你不起作用。试着创建一个新的数据库,看看它是否工作。我复制粘贴了它,它给出了依赖项错误。如果我使用[Required]属性,它将起作用。您的解决方案不起作用,您没有定义principle表和dependent表。按照EF约定,没有必要这样做。我不知道为什么它对你不起作用。试着创建一个新的数据库,看看它是否工作。我复制粘贴了它,它给出了依赖项错误。如果我使用[Required]属性,它将起作用。如果我想在地址表中添加外键,该怎么办?在这种情况下,您将在Address类中添加一个具有ForeignKey属性的StudentId属性?如果我想在地址表中添加一个外键,该怎么办?在这种情况下,您将在Address类中添加一个具有ForeignKey属性的StudentId属性