当前位置:   article > 正文

.Net EF Core IEntityTypeConfiguration之CodeFirst实现(SqlServer)_ef ientitytypeconfiguration

ef ientitytypeconfiguration

针对.net core EF框架下的CodeFirst实现(Webapi项目)

1、配置文件appsettings.json配置数据库连接

  1. "ConnectionStrings": {
  2. "SOADBContext": "Data Source=.;Initial Catalog=RextecSOA;User=sa;Password=123456" //sqlserver
  3. }

2、startup 数据库连接

services.AddDbContext<SOADbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SOADBContext")));

3、IEntityTypeConfiguration 实现数据表映射

创建.net core 类库 Rextec.SOA.Configuring

实现代码:

 数据表通用字段映射(基础映射类)

  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.EntityFrameworkCore.Metadata.Builders;
  3. using Rextec.SOA.Repository;
  4. namespace Rextec.SOA.Configuring
  5. {
  6. /// <summary>
  7. /// 通用字段映射
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. public abstract class BaseConfiguring<T> : IEntityTypeConfiguration<T> where T : BaseModel
  11. {
  12. public virtual void Configure(EntityTypeBuilder<T> builder)
  13. {
  14. builder.HasKey(x => x.ID);
  15. builder.Property(x => x.CreateUserID).HasMaxLength(50).IsRequired();
  16. builder.Property(x => x.CreateUserName).HasMaxLength(50);
  17. builder.Property(x => x.CreateTime).HasColumnType("datetime");
  18. builder.Property(x => x.ModifyUserID).HasMaxLength(50);
  19. builder.Property(x => x.ModifyUserName).HasMaxLength(50);
  20. builder.Property(x => x.ModifyTime).HasColumnType("datetime");
  21. }
  22. }
  23. }

以用户表映射代码

  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;
  2. using Rextec.SOA.Repository;
  3. namespace Rextec.SOA.Configuring
  4. {
  5. /// <summary>
  6. /// 人员表映射
  7. /// </summary>
  8. public class UserInfoConfiguring:BaseConfiguring<UserInfo>
  9. {
  10. public override void Configure(EntityTypeBuilder<UserInfo> builder)
  11. {
  12. builder.Property(x => x.UserName).HasMaxLength(50);
  13. builder.Property(x => x.LoginAccount).HasMaxLength(50);
  14. builder.Property(x => x.LoginPassword).HasMaxLength(50);
  15. builder.Property(x => x.Tel).HasMaxLength(50);
  16. builder.Property(x => x.Email).HasMaxLength(50);
  17. builder.Property(x => x.Sex).HasMaxLength(50);
  18. builder.Property(x => x.IsEnable).HasMaxLength(1);
  19. builder.Property(x => x.DataLimit).HasMaxLength(1);
  20. builder.Property(x => x.IsAdmin).HasMaxLength(1);
  21. }
  22. }
  23. }

通用字段实体类对象代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Text;
  5. namespace Rextec.SOA.Repository
  6. {
  7. /// <summary>
  8. /// 通用字段实体类
  9. /// </summary>
  10. public abstract class BaseModel
  11. {
  12. /// <summary>
  13. /// 主键
  14. /// </summary>
  15. [Key,StringLength(50)]
  16. public string ID { get; set; } = Guid.NewGuid().ToString();
  17. /// <summary>
  18. /// 创建人
  19. /// </summary>
  20. [Required,StringLength(50)]
  21. public string CreateUserID { get; set; }
  22. /// <summary>
  23. /// 创建人姓名
  24. /// </summary>
  25. public string CreateUserName { get; set; }
  26. /// <summary>
  27. /// 创建时间
  28. /// </summary>
  29. public DateTime CreateTime { get; set; } = DateTime.Now;
  30. /// <summary>
  31. /// 修改人ID
  32. /// </summary>
  33. public string ModifyUserID { get; set; }
  34. /// <summary>
  35. /// 修改人姓名
  36. /// </summary>
  37. public string ModifyUserName { get; set; }
  38. /// <summary>
  39. /// 修改日期
  40. /// </summary>
  41. public DateTime? ModifyTime { get; set; }
  42. }
  43. }

人员实体类对象代码

  1. using System.ComponentModel.DataAnnotations.Schema;
  2. namespace Rextec.SOA.Repository
  3. {
  4. /// <summary>
  5. /// 用户信息表
  6. /// </summary>
  7. [Table("UserInfo")]
  8. public class UserInfo:BaseModel
  9. {
  10. /// <summary>
  11. /// 用户名
  12. /// </summary>
  13. public string UserName { get; set; }
  14. /// <summary>
  15. /// 登录名
  16. /// </summary>
  17. public string LoginAccount { get; set; }
  18. /// <summary>
  19. /// 登录密码
  20. /// </summary>
  21. public string LoginPassword { get; set; }
  22. /// <summary>
  23. /// 联系电话
  24. /// </summary>
  25. public string Tel { get; set; }
  26. /// <summary>
  27. /// 邮箱
  28. /// </summary>
  29. public string Email { get; set; }
  30. /// <summary>
  31. /// 性别 0:男 1:女
  32. /// </summary>
  33. public string Sex { get; set; }
  34. /// <summary>
  35. /// 性别描述
  36. /// </summary>
  37. [NotMapped]
  38. public string SexDescrib { get { return Sex == "0" ? "男" : (Sex == "1" ? "女" : ""); } }
  39. /// <summary>
  40. /// 是否可用 0 否 1:是 默认可用
  41. /// </summary>
  42. public int IsEnable { get; set; } = 1;
  43. /// <summary>
  44. /// 用户数据权限 1:本人 2:不限
  45. /// </summary>
  46. public int DataLimit { get; set; }
  47. /// <summary>
  48. /// 是否管理员 0:否 1:是 默认否
  49. /// </summary>
  50. public int IsAdmin { get; set; }
  51. }
  52. }

4、数据库上下文代码

  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.EntityFrameworkCore.Metadata.Builders;
  7. namespace Rextec.SOA.Repository
  8. {
  9. /// <summary>
  10. /// 数据库上下文
  11. /// </summary>
  12. public class SOADbContext:DbContext
  13. {
  14. /// <summary>
  15. ///
  16. /// </summary>
  17. /// <param name="options"></param>
  18. public SOADbContext(DbContextOptions<SOADbContext> options):base(options)
  19. {
  20. //Database.Migrate();//如果数据库不存在,则创建数据库(migrations创建)
  21. Database.EnsureCreated();//如果数据库不存在则创建则创建数据库
  22. }
  23. #region dbSet
  24. public virtual DbSet<UserInfo> UserInfos { get; set; }
  25. #endregion
  26. /// <summary>
  27. /// 数据库表初始化
  28. /// </summary>
  29. /// <param name="modelBuilder"></param>
  30. protected override void OnModelCreating(ModelBuilder modelBuilder)
  31. {
  32. base.OnModelCreating(modelBuilder);
  33. try
  34. {
  35. //modelBuilder.ApplyConfiguration(new UserInfoConfiguring());//单个文件映射
  36. //var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
  37. string path = AppDomain.CurrentDomain.BaseDirectory;
  38. var files = Directory.GetFiles(path, "Rextec.SOA.Configuring.dll");
  39. if (files.Length > 0)
  40. {
  41. var typesToRegister = Assembly.LoadFile(files[0]).GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
  42. foreach (var type in typesToRegister)
  43. {
  44. if (!type.FullName.Contains("BaseConfiguring"))
  45. {
  46. dynamic configurationInstance = Activator.CreateInstance(type);
  47. modelBuilder.ApplyConfiguration(configurationInstance);
  48. }
  49. }
  50. }
  51. }
  52. catch (Exception ex)
  53. {
  54. }
  55. }
  56. }
  57. }

亲测:

使用Postman 调用接口;数据库不存在时,会自动创建数据库

自动创建的数据表如下

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/135127
推荐阅读
相关标签
  

闽ICP备14008679号