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

时间:2014-04-15 09:49:15

标签: c# entity-framework

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

用户表:

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

电脑桌:

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

2 个答案:

答案 0 :(得分:0)

这是用户和计算机之间的一对一关系:

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; }
    }

答案 1 :(得分:0)

参考您的代码:

[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;

 }

你可以看看Configure One-to-One Relationship