8.EntityFrameworkCore项目

愿你出走半生,归来仍是少年! 

 1.DbContext

        创建自己的DbContext并继承Abp的对应类和接口,实现基础的身份验证模块的数据库支持(基于Microsoft Identity 库 ),并配置PostGresql的Postgis插件检查等。

  [ReplaceDbContext(typeof(IIdentityDbContext))]
    [ReplaceDbContext(typeof(ITenantManagementDbContext))]
    [ConnectionStringName("Default")]
    public class DefaultDbContext :
        AbpDbContext<DefaultDbContext> ,
        IIdentityDbContext,
        ITenantManagementDbContext
    {

      
 

        #region 用户识别
         
        //用户管理
        public DbSet<IdentityUser> Users { get; set; }
        public DbSet<IdentityRole> Roles { get; set; }
        public DbSet<IdentityClaimType> ClaimTypes { get; set; }
        public DbSet<OrganizationUnit> OrganizationUnits { get; set; }
        public DbSet<IdentitySecurityLog> SecurityLogs { get; set; }    
        public DbSet<IdentityLinkUser> LinkUsers { get; set; }

        // 租户管理
        public DbSet<Tenant> Tenants { get; set; }
        public DbSet<TenantConnectionString> TenantConnectionStrings { get; set; }

        #endregion


        /// <summary>
        /// 默认的书户口连接
        /// </summary>
        /// <param name="options"></param>
        public DefaultDbContext(DbContextOptions<DefaultDbContext> options ) : base(options)
        {
            
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.HasPostgresExtension("postgis");//确认PG插件
            /* Include modules to your migration db context */

            builder.ConfigurePermissionManagement();//AbpPermissionGrants表
            builder.ConfigureSettingManagement();
            builder.ConfigureBackgroundJobs();
            builder.ConfigureAuditLogging();
            builder.ConfigureIdentity();
            //builder.ConfigureIdentityServer();
            builder.ConfigureFeatureManagement();
            builder.ConfigureTenantManagement();

            /* Configure your own tables/entities inside here */

            //SeedHelper seedHelper = new SeedHelper(_guidGenerator);
            //seedHelper.Seed(builder);
            
        }

    }

 2.种子数据

        创建自己的种子数据注入类,继承IDataSeedContributor接口,并实现数据创建。

 public class DefaultDbSeeder : IDataSeedContributor, ITransientDependency
    {
        private readonly IRepository<IdentityUser, Guid> _userRepository;

        private readonly IGuidGenerator _guidGenerator;

        private readonly IdentityUserManager _userManager;

        public DefaultDbSeeder(
            IGuidGenerator guidGenerator,
            IRepository<IdentityUser, Guid> userRepository,
            IdentityUserManager userManager )
        {
            _guidGenerator = guidGenerator;
            _userRepository = userRepository;
            _userManager = userManager;
        }

        public async Task SeedAsync(DataSeedContext context)
        {
            if (await _userRepository.GetCountAsync() <= 1)
            {
                var userSpe = new IdentityUser(_guidGenerator.Create(), "spe", "25@qq.com");
                userSpe.SetPhoneNumber("", true);
                userSpe.Name = "";
                 
                userSpe = await _userRepository.InsertAsync(
                    userSpe,
                    autoSave: true
                );

                await _userManager.AddPasswordAsync(userSpe, "1q2w3E*");

               await _userManager.SetRolesAsync(userSpe, new List<string>() { "admin" });


                var userHp = new IdentityUser(_guidGenerator.Create(), "hp", "@qq.com");
                userHp.SetPhoneNumber("", true);
                userHp.Name = "侯";

                userHp = await _userRepository.InsertAsync(
                    userHp,
                    autoSave: true
                );

                await _userManager.AddPasswordAsync(userHp, "1q2w3E*");

                await _userManager.SetRolesAsync(userHp, new List<string>() { "admin" });
            }
        }
    }

 3.实体字段扩展

        创建EfCoreEntityExtensionMappings静态类,配置实体的字段扩展

public static class EfCoreEntityExtensionMappings
    {
        private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();

        public static void Configure()
        {
            GlobalFeatureConfigurator.Configure();
            ExtensionConfigurator.Configure();

            OneTimeRunner.Run(() =>
            {
                /* You can configure extra properties for the
                 * entities defined in the modules used by your application.
                 *
                 * This class can be used to map these extra properties to table fields in the database.
                 *
                 * USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING.
                 * USE LandManagerModuleExtensionConfigurator CLASS (in the Domain.Shared project)
                 * FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES
                 *
                 * Example: Map a property to a table field:

                     ObjectExtensionManager.Instance
                         .MapEfCoreProperty<IdentityUser, string>(
                             "MyProperty",
                             (entityBuilder, propertyBuilder) =>
                             {
                                 propertyBuilder.HasMaxLength(128);
                             }
                         );

                 * See the documentation for more:
                 * https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities
                 */

                //Role添加NickName作为中文名称存储
                ObjectExtensionManager.Instance
                  .MapEfCoreProperty<IdentityRole, string>(
                      "NickName",
                      (entityBuilder, propertyBuilder) =>
                      {
                          propertyBuilder.HasMaxLength(32);
                      }
                  );
            });
        }
    }

 4.模块化文件

        创建模块化文件,并针对数据库、默认仓储、种子数据进行配置。

 /// <summary>
    /// EF模块
    /// </summary>
    [DependsOn(
        typeof(AbpEntityFrameworkCorePostgreSqlModule),
        typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        typeof(AbpIdentityEntityFrameworkCoreModule),
        typeof(AbpPermissionManagementEntityFrameworkCoreModule),
        typeof(AbpSettingManagementEntityFrameworkCoreModule),
        typeof(AbpBackgroundJobsEntityFrameworkCoreModule),
        typeof(AbpTenantManagementEntityFrameworkCoreModule),
        typeof(AbpFeatureManagementEntityFrameworkCoreModule),
        typeof(LandManagerDomainModule) 
        )]
    public class LandManagerEntityFrameworkCoreModule:AbpModule
    {

        

        public LandManagerEntityFrameworkCoreModule() { }

        public override void PreConfigureServices(ServiceConfigurationContext context)
        { 
            //解决PG DateTime with Kind=Local 问题
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

            EfCoreEntityExtensionMappings.Configure();
        }


        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddAbpDbContext<DefaultDbContext>(options =>
            {
                //面向实体和聚合根 提供默认仓储
                options.AddDefaultRepositories(includeAllEntities: true);
            });

            //PGSQL
            Configure<AbpDbContextOptions>(options =>
            { 
                options.UseNpgsql(o=>o.UseNetTopologySuite());//添加空间数据库支持
            });
        }


        public override void OnPostApplicationInitialization(ApplicationInitializationContext context)
        {
            //种子数据写入
            context.GetApplicationBuilder().ApplicationServices.GetRequiredService<IDataSeeder>().SeedAsync();
        }




    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就是那个帕吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值