3、创建Model
实体属性有数据批注和Fluent API两种,我们这里两种混合使用,实际项目中只需要一种就可以了。
Entity#
我们所有表基本都是有通用字段的,那么把这些通用字段放到一个父类中更好处理。
Copy
public class Entity
{
///
/// Id
///
[Key]
[Column(“id”)]
[Comment(“主键Id”)]
public int Id { get; set; }
///
/// 删除标识
///
[Column(“delete_flag”)]
[Comment(“删除标识”)]
public int DeleteFlag { get; set; }
///
/// 创建人
///
[Column(“created_by”)]
[Comment(“创建人”)]
public int CreatedBy { get; set; }
///
/// 创建时间
///
[Column(“created_time”)]
[Comment(“创建时间”)]
public DateTime CreatedTime { get; set; }
///
/// 更新人
///
[Column(“update_by”)]
[Comment(“更新人”)]
public int? UpdatedBy { get; set; }
///
/// 更新时间
///
[Column(“update_time”)]
[Comment(“更新时间”)]
public DateTime? UpdatedTime { get; set; }
}
4、Post(演示表)#
Author字段我们使用Fluent API
Copy
[Table(“tb_post”)]
public class Post : Entity
{
///
/// 标题
///
[Column(“title”)]
[Comment(“标题”)]
public string Title { get; set; }
///
/// 内容
///
[Column(“body”)]
[Comment(“内容”)]
public string Body { get; set; }
///
/// 作者 这里使用 Fluent API 方式去控制 具体见 LY.Admin.Repositories.Database.EntityConfigurations.PostConfiguration
///
public string Author { get; set; }
}
5、创建DbContext
如果使用Fluent API是需要在OnModelCreating进行设置的代码如下
DbContext#
Copy
public class LYAdminDbContext:DbContext
{
///
/// 构造函数 调用父类构造函数
///
///
public LYAdminDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region 实体属性
// 参考 https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties
// 可以使用 数据批注 或者 Fluent API
modelBuilder.ApplyConfiguration(new PostConfiguration());
#endregion
}
public DbSet<Post> Posts { get; set; }
}
PostConfiguration#
这里是每个实体类都单独写的,更多API查看实体属性
Copy
///
/// 实体属性
/// 参考 https://docs.microsoft.com/zh-cn/ef/core/modeling/entity-properties
/// 可以使用 数据批注 或者 Fluent API
///
public class PostConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.Property(x => x.Author).HasMaxLength(50).HasColumnType(“varchar(50)”).HasColumnName(“author”).HasComment(“作者”);
}
}
6、LY.Admin.Web
修改Startup#
Copy
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<LYAdminDbContext>(options =>
{
var connectionString = this.Configuration["ConnectionStrings:MySqlConn"];
//这里现在需要指定版本,暂时设置为自动检测
options.UseMySql(connectionString,ServerVersion.AutoDetect(connectionString));
});
}
appsettings.json配置连接字符串#
Copy
{
“Logging”: {
“LogLevel”: {
“Default”: “Information”,
“Microsoft”: “Warning”,
“Microsoft.Hosting.Lifetime”: “Information”
}
},
“AllowedHosts”: “*”,
“ConnectionStrings”: {
“MySqlConn”: “Server=127.0.0.1;Port=3306;Database=lyadmin;Uid=root;Pwd=123456;charset=utf8;Allow User Variables=True”
}
}
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com