在EF Core中,可以使用以下代码示例来定义包含具有递归属性的导航属性:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public int? ParentCategoryId { get; set; }
public Category ParentCategory { get; set; }
public ICollection ChildCategories { get; set; }
}
在上面的示例中,Category类具有一个ParentCategory导航属性,该属性指向父级Category对象,并且有一个ChildCategories导航属性,该属性是一个集合,包含所有子级Category对象。
请注意,在ParentCategoryId属性上使用了可空类型int?,这是为了处理根级别的Category对象,即没有父级的情况。如果ParentCategoryId为null,则表示该Category对象是根级别。
要在EF Core中使用这些导航属性,您需要配置实体关系。可以使用OnModelCreating方法来配置这些关系:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasOne(c => c.ParentCategory)
.WithMany(c => c.ChildCategories)
.HasForeignKey(c => c.ParentCategoryId)
.OnDelete(DeleteBehavior.Restrict);
}
在上面的示例中,我们使用HasOne和WithMany方法定义了父子关系。HasForeignKey方法指定了外键属性,并使用OnDelete方法指定了级联删除行为(在这种情况下,禁止级联删除)。
然后,您可以使用这些导航属性来进行查询和操作,例如:
// 查询所有根级别的Category对象
var rootCategories = dbContext.Categories.Where(c => c.ParentCategoryId == null).ToList();
// 查询特定Category对象的子级Category对象
var categoryId = 1;
var category = dbContext.Categories.Include(c => c.ChildCategories).FirstOrDefault(c => c.CategoryId == categoryId);
var childCategories = category?.ChildCategories.ToList();
// 创建一个新的Category对象,并将其添加为现有Category对象的子级
var newCategory = new Category { Name = "Child Category" };
category.ChildCategories.Add(newCategory);
dbContext.SaveChanges();
上面的示例演示了如何使用导航属性进行查询和操作。可以根据您的需求对其进行调整。