我有解决方案,其中独立的类库项目(没有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
我错过了什么。先谢了。
1条答案
按热度按时间3ks5zfa01#
您只能将
IDesignTimeDbContextFactory
用于类库,并且应该为迁移命令安装Microsoft.EntityFrameworkCore.Tools
。数据库上下文: