两个实体中,如果一个实体的一个实例与另一个实体相关,则我们就叫做一对一关系

查看如下代码:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}
     
public class StudentAddress 
{
    public int StudentAddressId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

 

这里,Student类只能拥有零个或最多一个StudentAddress类,所以符合一对一关系

在SQL Server数据库中,一对一关系发生在当一张表的主键是另一张表的主键或外键时,所以如上代码中,我们要配置StudentId为主键,StudentAddressId既为主键也为外键。

1.使用DataAnnotations配置一对零或一对一关系:

Student类会根据Code-First默认约定将StudentId属性配置为主键,所以这里我们就不用额外的配置它了。

StudentAddress类中,我们需要配置StudentAddressId既为主键又为外键,同样的,Code-First默认约定会将StudentAddressId配置为主键,所以这里我们仅仅需要使用[ForeignKey("Student")]特性将StudentAddressId属性配置为外键即可。

代码如下:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}
     
public class StudentAddress 
{
    [ForeignKey("Student")]
    public int StudentAddressId { get; set; }
        
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-03-05
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-06-19
  • 2022-12-23
  • 2021-10-03
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案