简体   繁体   English

如何正确设置一对一关系?

[英]How to properly set a one-to-one relationship?

How to properly set a one-to-one relationship, please? 请问如何正确设置一对一的关系?

User table: 用户表:

[Table("User")]
class User{
 [Key]
 public int idUser;
 public int idComputer; //ForeignKey
}

Computer table: 电脑桌:

[Table("Computer")]
class Computer{
 [Key]
 public int idComputer;
}

This is one-to-one relationship of User and Computer: 这是用户和计算机的一对一关系:

public class User
    {
        public User() 
        { 
        }

        public int idUser; { get; set; }
        [Required]
        public string UserName { get; set; }


        public virtual Computer Computer{ get; set; }

    }


public class Computer
    {
        public Computer() 
        {
        }
        [Key, ForeignKey("User")]
        public int idUser{ get; set; }

        public string ComputerName {get;set;}

        public virtual User User { get; set; }
    }

Referring your code: 引用您的代码:

[Table("User")]
public class User
 {
  [Key]
  public int idUser;
  public int idComputer; 
  public virtual Computer Computer;
 } 

[Table("Computer")]
 public class Computer
 {

  [Key, ForeignKey("User")]
  public int idComputer;
  public virtual User User;

 }

You can have look here Configure One-to-One Relationship 您可以在这里配置一对一关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM