赞
踩
针对.net core EF框架下的CodeFirst实现(Webapi项目)
1、配置文件appsettings.json配置数据库连接
- "ConnectionStrings": {
- "SOADBContext": "Data Source=.;Initial Catalog=RextecSOA;User=sa;Password=123456" //sqlserver
- }
2、startup 数据库连接
services.AddDbContext<SOADbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SOADBContext")));
3、IEntityTypeConfiguration 实现数据表映射
创建.net core 类库 Rextec.SOA.Configuring
实现代码:
数据表通用字段映射(基础映射类)
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Metadata.Builders;
- using Rextec.SOA.Repository;
-
- namespace Rextec.SOA.Configuring
- {
- /// <summary>
- /// 通用字段映射
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public abstract class BaseConfiguring<T> : IEntityTypeConfiguration<T> where T : BaseModel
- {
- public virtual void Configure(EntityTypeBuilder<T> builder)
- {
- builder.HasKey(x => x.ID);
- builder.Property(x => x.CreateUserID).HasMaxLength(50).IsRequired();
- builder.Property(x => x.CreateUserName).HasMaxLength(50);
- builder.Property(x => x.CreateTime).HasColumnType("datetime");
- builder.Property(x => x.ModifyUserID).HasMaxLength(50);
- builder.Property(x => x.ModifyUserName).HasMaxLength(50);
- builder.Property(x => x.ModifyTime).HasColumnType("datetime");
- }
- }
- }
以用户表映射代码
- using Microsoft.EntityFrameworkCore.Metadata.Builders;
- using Rextec.SOA.Repository;
-
- namespace Rextec.SOA.Configuring
- {
- /// <summary>
- /// 人员表映射
- /// </summary>
- public class UserInfoConfiguring:BaseConfiguring<UserInfo>
- {
- public override void Configure(EntityTypeBuilder<UserInfo> builder)
- {
- builder.Property(x => x.UserName).HasMaxLength(50);
- builder.Property(x => x.LoginAccount).HasMaxLength(50);
- builder.Property(x => x.LoginPassword).HasMaxLength(50);
- builder.Property(x => x.Tel).HasMaxLength(50);
- builder.Property(x => x.Email).HasMaxLength(50);
- builder.Property(x => x.Sex).HasMaxLength(50);
- builder.Property(x => x.IsEnable).HasMaxLength(1);
- builder.Property(x => x.DataLimit).HasMaxLength(1);
- builder.Property(x => x.IsAdmin).HasMaxLength(1);
- }
- }
- }
通用字段实体类对象代码
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Text;
-
- namespace Rextec.SOA.Repository
- {
- /// <summary>
- /// 通用字段实体类
- /// </summary>
- public abstract class BaseModel
- {
- /// <summary>
- /// 主键
- /// </summary>
- [Key,StringLength(50)]
- public string ID { get; set; } = Guid.NewGuid().ToString();
- /// <summary>
- /// 创建人
- /// </summary>
- [Required,StringLength(50)]
- public string CreateUserID { get; set; }
- /// <summary>
- /// 创建人姓名
- /// </summary>
- public string CreateUserName { get; set; }
- /// <summary>
- /// 创建时间
- /// </summary>
- public DateTime CreateTime { get; set; } = DateTime.Now;
- /// <summary>
- /// 修改人ID
- /// </summary>
- public string ModifyUserID { get; set; }
- /// <summary>
- /// 修改人姓名
- /// </summary>
- public string ModifyUserName { get; set; }
- /// <summary>
- /// 修改日期
- /// </summary>
- public DateTime? ModifyTime { get; set; }
- }
- }
人员实体类对象代码
- using System.ComponentModel.DataAnnotations.Schema;
-
- namespace Rextec.SOA.Repository
- {
- /// <summary>
- /// 用户信息表
- /// </summary>
- [Table("UserInfo")]
- public class UserInfo:BaseModel
- {
- /// <summary>
- /// 用户名
- /// </summary>
- public string UserName { get; set; }
- /// <summary>
- /// 登录名
- /// </summary>
- public string LoginAccount { get; set; }
- /// <summary>
- /// 登录密码
- /// </summary>
- public string LoginPassword { get; set; }
- /// <summary>
- /// 联系电话
- /// </summary>
- public string Tel { get; set; }
- /// <summary>
- /// 邮箱
- /// </summary>
- public string Email { get; set; }
- /// <summary>
- /// 性别 0:男 1:女
- /// </summary>
- public string Sex { get; set; }
- /// <summary>
- /// 性别描述
- /// </summary>
- [NotMapped]
- public string SexDescrib { get { return Sex == "0" ? "男" : (Sex == "1" ? "女" : ""); } }
- /// <summary>
- /// 是否可用 0 否 1:是 默认可用
- /// </summary>
- public int IsEnable { get; set; } = 1;
- /// <summary>
- /// 用户数据权限 1:本人 2:不限
- /// </summary>
- public int DataLimit { get; set; }
- /// <summary>
- /// 是否管理员 0:否 1:是 默认否
- /// </summary>
- public int IsAdmin { get; set; }
- }
- }
4、数据库上下文代码
- using System;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Metadata.Builders;
-
- namespace Rextec.SOA.Repository
- {
- /// <summary>
- /// 数据库上下文
- /// </summary>
- public class SOADbContext:DbContext
- {
- /// <summary>
- ///
- /// </summary>
- /// <param name="options"></param>
- public SOADbContext(DbContextOptions<SOADbContext> options):base(options)
- {
- //Database.Migrate();//如果数据库不存在,则创建数据库(migrations创建)
- Database.EnsureCreated();//如果数据库不存在则创建则创建数据库
- }
- #region dbSet
- public virtual DbSet<UserInfo> UserInfos { get; set; }
- #endregion
-
- /// <summary>
- /// 数据库表初始化
- /// </summary>
- /// <param name="modelBuilder"></param>
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- base.OnModelCreating(modelBuilder);
- try
- {
- //modelBuilder.ApplyConfiguration(new UserInfoConfiguring());//单个文件映射
- //var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
- string path = AppDomain.CurrentDomain.BaseDirectory;
- var files = Directory.GetFiles(path, "Rextec.SOA.Configuring.dll");
- if (files.Length > 0)
- {
- var typesToRegister = Assembly.LoadFile(files[0]).GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
- foreach (var type in typesToRegister)
- {
- if (!type.FullName.Contains("BaseConfiguring"))
- {
- dynamic configurationInstance = Activator.CreateInstance(type);
- modelBuilder.ApplyConfiguration(configurationInstance);
- }
- }
- }
- }
- catch (Exception ex)
- {
-
- }
- }
- }
- }
亲测:
使用Postman 调用接口;数据库不存在时,会自动创建数据库
自动创建的数据表如下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。