Entity framework 在代码优先实体框架中,当两个表之间有两个关系时,我如何设计模型?
我必须实体{人,孩子}每个人都有很多孩子,一个孩子,它本身就是一个人,我们必须在这里建立关系,孩子和人之间的一对一关系,以及另一种人和孩子之间的一对多关系Entity framework 在代码优先实体框架中,当两个表之间有两个关系时,我如何设计模型?,entity-framework,Entity Framework,我必须实体{人,孩子}每个人都有很多孩子,一个孩子,它本身就是一个人,我们必须在这里建立关系,孩子和人之间的一对一关系,以及另一种人和孩子之间的一对多关系 public class Child { [Key] [System.ComponentModel.DataAnnotations.Schema.ForeignKey("person")] public int IDperson { get; set; } public virtual Person perso
public class Child
{
[Key]
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("person")]
public int IDperson { get; set; }
public virtual Person person { get; set; }
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("parent")]
[System.ComponentModel.DataAnnotations.Required]
public int IDparent { get; set; }
public virtual Person parent { get; set; }
}
public class Person
{
[System.ComponentModel.DataAnnotations.Key]
public int ID { get; set; }
[System.ComponentModel.DataAnnotations.MaxLength(50)]
[System.ComponentModel.DataAnnotations.Required]
public String name { get; set; }
public virtual System.Collections.Generic.IList<Child> children { get; set; }
}
公共类子类
{
[关键]
[System.ComponentModel.DataAnnotations.Schema.ForeignKey(“person”)]
公共整数IDperson{get;set;}
公共虚拟人{get;set;}
[System.ComponentModel.DataAnnotations.Schema.ForeignKey(“父”)]
[System.ComponentModel.DataAnnotations.Required]
公共int IDparent{get;set;}
公共虚拟人父项{get;set;}
}
公共阶层人士
{
[System.ComponentModel.DataAnnotations.Key]
公共int ID{get;set;}
[System.ComponentModel.DataAnnotations.MaxLength(50)]
[System.ComponentModel.DataAnnotations.Required]
公共字符串名称{get;set;}
public virtual System.Collections.Generic.IList子项{get;set;}
}
我写这些是为了人际关系,这样可以吗 正如Jeroen所建议的,继承在您的场景中可能很有用:
public class Child : Person
{
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("parent")]
[System.ComponentModel.DataAnnotations.Required]
public int IDparent { get; set; }
public virtual Person parent { get; set; }
}
public class Person
{
[System.ComponentModel.DataAnnotations.Key]
public int ID { get; set; }
[System.ComponentModel.DataAnnotations.MaxLength(50)]
[System.ComponentModel.DataAnnotations.Required]
public String name { get; set; }
public virtual System.Collections.Generic.IList<Child> children { get; set; }
}
公共类子类:Person
{
[System.ComponentModel.DataAnnotations.Schema.ForeignKey(“父”)]
[System.ComponentModel.DataAnnotations.Required]
公共int IDparent{get;set;}
公共虚拟人父项{get;set;}
}
公共阶层人士
{
[System.ComponentModel.DataAnnotations.Key]
公共int ID{get;set;}
[System.ComponentModel.DataAnnotations.MaxLength(50)]
[System.ComponentModel.DataAnnotations.Required]
公共字符串名称{get;set;}
public virtual System.Collections.Generic.IList子项{get;set;}
}
为什么不让孩子从人身上延伸出来?然后您可以删除人际关系