.net 类库工程中如何先用EF核心代码创建数据库

yhived7q  于 2023-01-14  发布在  .NET
关注(0)|答案(1)|浏览(120)

我有解决方案,其中独立的类库项目(没有Web API/MVC项目)在. NET 6。我没有添加任何启动项目作为Web API或MVC。我已经添加了模型和DB上下文类在该项目如下。

public class Producer
{

    [Key]
    public int ProducerID { get; set; }

    [Required]
    [StringLength(254)]
    public string Name { get; set; }

    public ICollection<Product> Products { get; set; }
}
public class Product
    {

        [Key]
        public int ProductID { get; set; }

        public int ProducerID { get; set; }

        [Required]
        [StringLength(254)]
        public string Name { get; set; }

        public Producer Producer { get; set;}
    }

在我的DBContext类代码如下.

public class AppDbContext : DbContext
    {
        private readonly string _connectionString;
        private readonly IConfiguration _iConfig;
        public AppDbContext(DbContextOptions<AppDbContext> options, IConfiguration iConfig) : base(options) {
            _connectionString = GetConnectionString(iConfig);
            _iConfig = iConfig;
        }

        public static string GetConnectionString(IConfiguration iConfig)
        {
            var dataSource = iConfig["db:serverName"];
            var port = iConfig["db:port"];
            if (!string.IsNullOrWhiteSpace(port))
                dataSource += "," + port;

            SqlConnectionStringBuilder builder = new()
            {
                ["Data Source"] = dataSource,
                ["Initial Catalog"] = iConfig["db:initialCatalog"],
                ["User ID"] = iConfig["db:userId"],
                ["Password"] = iConfig["db:password"]
            };

            return builder.ConnectionString;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                              => optionsBuilder.UseSqlServer(_connectionString);

        public DbSet<Producer> Producers { get; set; }
        public DbSet<Product> Products { get; set; }

    }

当我运行add-migration命令时,我收到一条错误消息
无法创建类型为"AppDbContext"的对象。有关设计时支持的不同模式,请参见https://go.microsoft.com/fwlink/?linkid=851728
我错过了什么。先谢了。

3ks5zfa0

3ks5zfa01#

您只能将IDesignTimeDbContextFactory用于类库,并且应该为迁移命令安装Microsoft.EntityFrameworkCore.Tools

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true");

        return new AppDbContext(optionsBuilder.Options);
    }
}

数据库上下文:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }
    public DbSet<Product> Products { get; set; }
}

相关问题