在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();
上面的示例演示了如何使用导航属性进行查询和操作。可以根据您的需求对其进行调整。