public class Persons
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
[MaxLength(20)]
public string Name { get; set; }
[MaxLength(11)]
public string Phone { get; set; }
[MaxLength(20)]
public string Wechat { get; set; }
public bool RecvMsg { get; set; }
public bool RecvWx { get; set; }
// 外键(出)
public ICollection<Buildings> Buildings { get; set; }
}
public class Buildings
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BuildingId { get; set; }
public int ParentId { get; set; }
[Required]
public string Caption { get; set; }
public int DeviceId { get; set; }
[ForeignKey("Persons")]
public int PersonId { get; set; }
[DecimalPrecision(5, 2)]
public decimal MinTem { get; set; }
[DecimalPrecision(5, 2)]
public decimal MaxTem { get; set; }
[DecimalPrecision(5, 2)]
public decimal MinHum { get; set; }
[DecimalPrecision(5, 2)]
public decimal MaxHum { get; set; }
public DateTime NextAlertTime { get; set; }
// 外键(入)
public virtual Persons Persons { get; set; }
}
注意,要在源表中声明ICollection以表示哪张表引用了此表
然后在引用外键的表中声明virtual类型的表实体(virtual用于延迟加载避免资源开销)

在使用Entity Framework Code First时,设置外键以建立主从关系的关键在于源表中声明`ICollection`,这表明另一表对此表的引用。而在被引用的表中,通过声明`virtual`类型的表实体实现延迟加载,以减少资源消耗。
922

被折叠的 条评论
为什么被折叠?



