IDesignTimeDbContextFactory 方式创建 DbContext

新建 实现 DbContext

using Microsoft.EntityFrameworkCore;
using PoemGame.Domain.GameAggregate;
using PoemGame.Domain.PlayerAggregate;
using PoemGame.Domain.Seedwork;
using PoemGame.Events.Shared;
using PoemGame.UOW;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PoemGame.Repository.EF
{
    public class PoemGameDbContext:DbContext, IUnitOfWork
    {
        private readonly ILocalEventBus _localeventBus = default!;
        private readonly IOutBoundEventBus _remoteeventBus = default!;
        //public PoemGameDbContext() { }
        public PoemGameDbContext(DbContextOptions<PoemGameDbContext> options):base(options)
        {

        }
        /// <summary>
        /// 带有事件发布的构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <param name="localeventBus"></param>
        /// <param name="remoteEventBus"></param>
        public PoemGameDbContext(DbContextOptions<PoemGameDbContext> options
            , ILocalEventBus localeventBus, IOutBoundEventBus remoteEventBus) : base(options)
        {
            _localeventBus = localeventBus;
            _remoteeventBus = remoteEventBus;
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new PlayerEntityTypeConfiguration());
            modelBuilder.ApplyConfiguration(new GameEntityTypeConfiguration());

            // modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
        /// <summary>
        /// 重载的方式 需要无参数构造函数
        /// </summary>
        /// <param name="optionsBuilder"></param>
        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    // base.OnConfiguring(optionsBuilder);
        //    optionsBuilder.UseMySql("Server=192.168.0.196;Database=NewDDD;uid=root;pwd=123456;",
        //        new MySqlServerVersion(new Version(8, 0, 27)));
        //    optionsBuilder.LogTo(item => { Console.WriteLine(item); });
        //}
        public DbSet<Game> Games { get; set; }
        public DbSet<Player> Players { get; set; }
        public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            var modifiedChanges =
                ChangeTracker.Entries()
                .Where(x => x.State == EntityState.Modified || x.State == EntityState.Added).ToList();
            var localEvents = new List<EventRecordLocal>();
            var remoteEvents = new List<EventRecordOutBound>();
            foreach (var change in modifiedChanges)
            {
                var entity = change.Entity as AggregateRoot;
                if (entity != null)
                {
                    foreach (var e in entity.GetLocalDomainEvents())
                    {
                        localEvents.Add(e);
                    }
                    entity.ClearLocalDomainEvents();
                    foreach (var e in entity.GetOutBoundDomainEvents())
                    {
                        remoteEvents.Add(e);
                    }
                    entity.ClearOutBoundDomainEvents();
                }
            }
            if (_localeventBus != null)
            {
                foreach (var e in localEvents)
                {
                    await _localeventBus.PublishAsync(e.EventData);
                }
            }
            var res = await base.SaveChangesAsync();
            if (_remoteeventBus != null)
            {
                foreach (var e in remoteEvents)
                {
                    await _remoteeventBus.PublishAsync(e.EventData);
                }
            }
            return res;
        }
    }
}

  

.MySql 方式

PoemGame.Repository.EF.MySqlServer  项目引用

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySqlConnector" Version="2.3.5" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\PoemGame.Repository.EF\PoemGame.Repository.EF.csproj" />
  </ItemGroup>
</Project>

  

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using System.Reflection;

namespace PoemGame.Repository.EF.MySqlServer
{
    public class DesignDbContextFactory : IDesignTimeDbContextFactory<PoemGameDbContext>
    {
        public PoemGameDbContext CreateDbContext(string[] args)
        {
            var connectionString = "Server=192.168.0.196;Database=NewDDD;uid=root;pwd=123456;";
            var serverVersion = new MySqlServerVersion(new Version(8, 0, 27));
            DbContextOptionsBuilder<PoemGameDbContext> optionsBuilder = new DbContextOptionsBuilder<PoemGameDbContext>();
            optionsBuilder.UseMySql(connectionString, serverVersion, mysqlOptions =>mysqlOptions.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().FullName));
            return new PoemGameDbContext(optionsBuilder.Options);
        }
    }
}

  

SQLite 方式

PoemGame.Repository.EF.SQLite  项目引用

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.2" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\PoemGame.Repository.EF\PoemGame.Repository.EF.csproj" />
  </ItemGroup>
</Project>

  

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace PoemGame.Repository.EF.SQLite
{
    public class DesignDbContextFactory : IDesignTimeDbContextFactory<PoemGameDbContext>
    {
        public PoemGameDbContext CreateDbContext(string[] args)
        {
            var folder = Environment.SpecialFolder.LocalApplicationData;
            var path = Environment.GetFolderPath(folder);
            var DbPath = System.IO.Path.Join(path, "poemgame.db");
            var optionsBuilder = new DbContextOptionsBuilder<PoemGameDbContext>();
            optionsBuilder.UseSqlite($"Data Source={DbPath}",
                x => x.MigrationsAssembly("PoemGame.Repository.EF.SQLite"));
            return new PoemGameDbContext(optionsBuilder.Options);
        }
    }
}

  

SqlServer 方式

PoemGame.Repository.EF.SqlServer  项目引用

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\PoemGame.Repository.EF\PoemGame.Repository.EF.csproj" />
  </ItemGroup>
</Project>

  

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace PoemGame.Repository.EF.SqlServer
{
    public class DesignDbContextFactory : IDesignTimeDbContextFactory<PoemGameDbContext>
    {
        public PoemGameDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<PoemGameDbContext>();
            optionsBuilder.UseSqlServer("Server=(local);Database=MyPoemGame;uid=sa;pwd=pwd;Encrypt=False",
                x => x.MigrationsAssembly("PoemGame.Repository.EF.SqlServer"));
            return new PoemGameDbContext(optionsBuilder.Options);
        }
    }
}

  

 

 

 

脚本生成

script-migration

 

 

 

 

带有版本号的脚本生成

script-migration -idempotent

 

posted on 2024-02-19 22:48  是水饺不是水饺  阅读(87)  评论(0)    收藏  举报

导航