实体是起点和核心,它表示了我们如何使用编程语言来描述业务对象。
定义实体,只要遵循EntityFramework Core
的规范要求,并配置好关系即可。
我们将通过实现一个简单但相对完整的博客示例来演示如何使用Ater.Dry来完成实际业务的开发。
所有的实体继承EntityBase
抽象类,具体定义如下:
// Blog.cs [Index(nameof(Title))] [Module(Modules.CMS)] public class Blog : EntityBase { /// <summary> /// 标题 /// </summary> [MaxLength(100)] public required string Title { get; set; } /// <summary> /// 描述 /// </summary> [MaxLength(300)] public string? Description { get; set; } /// <summary> /// 内容 /// </summary> [MaxLength(10000)] public required string Content { get; set; } /// <summary> /// 作者 /// </summary> [MaxLength(200)] public required string Authors { get; set; } /// <summary> /// 标题 /// </summary> [MaxLength(200)] public string? TranslateTitle { get; set; } /// <summary> /// 是否审核 /// </summary> public bool IsAudit { get; set; } /// <summary> /// 是否公开 /// </summary> public bool IsPublic { get; set; } = true; /// <summary> /// 是否原创 /// </summary> public bool IsOriginal { get; set; } [ForeignKey(nameof(UserId))] public required User User { get; set; } public Guid UserId { get; set; } /// <summary> /// 所属目录 /// </summary> [ForeignKey(nameof(CatalogId))] public Catalog Catalog { get; set; } = null!; public Guid CatalogId { get; set; } /// <summary> /// 浏览量 /// </summary> public int ViewCount { get; set; } }
// Catalog.cs [Index(nameof(Name))] [Index(nameof(Level))] [Module(Modules.CMS)] public class Catalog : EntityBase, ITreeNode<Catalog> { /// <summary> /// 目录名称 /// </summary> [MaxLength(50)] public required string Name { get; set; } /// <summary> /// 层级 /// </summary> public short Level { get; set; } /// <summary> /// 子目录 /// </summary> public List<Catalog> Children { get; set; } = []; /// <summary> /// 父目录 /// </summary> [ForeignKey(nameof(ParentId))] public Catalog? Parent { get; set; } public Guid? ParentId { get; set; } public ICollection<Blog> Blogs { get; set; } = []; [ForeignKey(nameof(UserId))] public User User { get; set; } = null!; public Guid UserId { get; set; } }
然后我们在User.cs
中添加实体的关联,以让EF Core能够清晰的知道它们1对N的关系:
// User.cs // ... exist codes public ICollection<Blog> Blogs { get; set; } = []; public ICollection<Catalog> Catalogs { get; set; } = [];
Important
强烈建议显示配置导航属性的外键,这在很多场景会非常有用!
实体添加完成后,我们在数据库上下文中添加上DbSet,这是推荐的做法,以便能够方法的调用。
// DefaultDbContext.cs // ... exist codes public DbSet<Catalog> Catalogs { get; set; } public DbSet<Blog> Blogs { get; set; }
Ok,现在我们已经完成了定义,这一步并不复杂,也全部在EntityFramework Core
的范畴。你可以使用任何EntityFramework Core
支持的方式来定义实体关系,没有任何特殊之处。
内容大纲