
Smartstore域实体开发实战如何为模块新增数据表并快速实现CRUD【免费下载链接】SmartstoreA modular, scalable and ultra-fast open-source all-in-one eCommerce platform built on ASP.NET Core 10项目地址: https://gitcode.com/GitHub_Trending/smar/Smartstore在 Smartstore 电商平台的模块开发中域实体Domain Entity是你为自己模块新增数据库表、实现数据增删改查CRUD的核心方式。本文将带你完成一套完整流程定义实体类 → 编写迁移建表 → 挂接到数据上下文 → 执行标准 CRUD 操作让新手也能快速上手模块数据开发。先了解架构一张表背后需要哪三块拼图Smartstore 基于 Entity Framework Core 访问数据库每张表都对应一个继承自BaseEntity的实体类型。为模块新增一张数据表本质上就是完成三件事拼图作用关键位置① 域实体类用 C# 类描述表结构与字段模块的Domain/目录② 迁移类Migration应用启动时自动建表、加索引模块的Migrations/目录③ DbContext 扩展让SmartDbContext能看到这张表模块的Extensions/目录官方教程完整描述了这套流程可参考creating-a-domain-entity.md。下面以仓库中真实的 Google Merchant Center 模块为例拆解。第一步编写域实体类BaseEntity 帮你省去主键所有实体都要继承抽象基类 BaseEntity——它会自动提供自增主键Id所以你不需要自己声明标识符属性也内置了是否为临时记录IsTransientRecord等实用判断。看一个真实示例GoogleProduct.cs 实体类用特性声明表名与索引[Table(GoogleProduct)] [Index(nameof(ProductId))] public class GoogleProduct : BaseEntity, IDefaultable { public int ProductId { get; set; } [StringLength(4000)] public string Taxonomy { get; set; } public bool Export { get; set; } true; // ... 其余字段 }三个小技巧 用[Table(表名)]显式指定表名避免与内置表重名 高频查询字段如ProductId加上[Index]索引 字符串字段用[StringLength(n)]明确长度防止生成过大的列类型第二步编写迁移类应用启动时自动建表Smartstore 使用 FluentMigrator 管理数据库结构变更支持 SQL Server、MySQL、PostgreSQL、SQLite 四种数据库一套迁移代码跨库通用详见 database-migrations.md。迁移文件命名遵循YYYYMMDDHHMMSS_迁移名.cs模式例如 20211206113000_Initial.cs[MigrationVersion(2021-12-06 11:30:00, GoogleMerchantCenter: Initial)] internal class Initial : Migration { public override void Up() { if (!Schema.Table(GoogleProduct).Exists()) { Create.Table(GoogleProduct) .WithIdColumn() // 自动生成 Id 主键列 .WithColumn(nameof(GoogleProduct.ProductId)).AsInt32().NotNullable().Indexed() .WithColumn(nameof(GoogleProduct.Taxonomy)).AsString(4000).Nullable(); // ... } } }最佳实践有两点建表前先做存在性检查Schema.Table(...).Exists()迁移可安全地重复执行初始迁移的Down()保持空实现——用户可能已经存了大量数据卸载模块时不要贸然删表第三步扩展 SmartDbContext打通数据通道Smartstore 的数据访问统一入口是 SmartDbContext。模块需要提供一个静态扩展类声明一张表对应一个DbSetT参考 SmartDbContextExtensions.cspublic static class SmartDbContextExtensions { public static DbSetGoogleProduct GoogleProducts(this SmartDbContext db) db.SetGoogleProduct(); }同时别忘了在模块的 Startup 中注册模型程序集这样 EF Core 才会把GoogleProduct纳入模型映射。至此三步拼图全部完成。CRUD 实战用 LINQ 完成增删改查在任意服务或控制器中注入SmartDbContext即可完成标准 CRUD// Create 新增 db.GoogleProducts().Add(new GoogleProduct { ProductId 10, Export true }); await db.SaveChangesAsync(); // Read 查询带分页 var page await db.GoogleProducts() .Where(x x.ProductId 10) .ToPagedListAsync(1, 20); // Update 更新 product.Taxonomy Electronics/Smartphones; await db.SaveChangesAsync(); // Delete 删除 db.GoogleProducts().Remove(product); await db.SaveChangesAsync(); 进阶能力ToPagedList分页、AsNoTracking()无跟踪查询提速、二级缓存AsCaching让重复查询直接命中内存均已在 contenteditable="false">【免费下载链接】SmartstoreA modular, scalable and ultra-fast open-source all-in-one eCommerce platform built on ASP.NET Core 10项目地址: https://gitcode.com/GitHub_Trending/smar/Smartstore创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考