在实际的项目开发中,可能会遇到同一张表同时保存自身和上级(或下级)的信息(一般是通过设置一个上级主键【ParentId】的列与主键【Id】关系)
例如:城市库,有国家、省、市...,省的ParentId是国家的Id,同理市的ParentId是省的Id
class="code_img_closed" src="/Upload/Images/2017102023/0015B68B3C38AA5B.gif" alt="">
public class City
{
/// <summary>
/// Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 上级Id
/// </summary>
public int? ParentId { get; set; }
/// <summary>
/// 下级地区
/// </summary>
public virtual ICollection<City> ChildCitys { get; set; }
/// <summary>
/// 上级地区
/// </summary>
public virtual City Parent { get; set; }
}
logs_code_collapse" style="font-size: 18px">View Code
public class CityMap : EntityTypeConfiguration<City>
{
public CityMap()
{
ToTable("City");
HasKey(c => c.Id);
Property(c => c.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
Property(c => c.Name).HasMaxLength(50);
//配置关系
HasMany(c => c.ChildCitys).WithOptional(c => c.Parent).HasForeignKey(k => k.ParentId);
}
}
View Code
static void Main(string[] args)
{
var country = new City { Name="中国" };
var province = new City { Name = "广东省" };
var citys = new List<City>
{
new City { Name="广州" },
new City { Name="深圳" },
new City { Name="珠海" }
};
province.ChildCitys = citys;
country.ChildCitys = new List<City> { province };
EFContext<City> context = new EFContext<City>();
context.Table.Add(country);
context.SaveChanges();
Console.WriteLine("ok");
Console.ReadKey();
}
View Code
运行控制台程序
然后查看数据库:
示例使用的是Entity Framework 6.X,同时上面的关系是0..1←→N,因为国家没有上级(ParentId为null)