Skip to main content
 首页 » 编程设计

c#之ASP.NET 5 控制台应用程序(包)之如何从连接字符串创建 DBContext

2024年02月05日22hnrainll

我正在尝试从 .net 核心上的连接字符串创建 DBContext。这曾经与 .net 4.5 一起工作:

public class MyContext : DbContext 
{ 
   internal MYContext(string connectionString) : base(connectionString){} 
} 

现在我收到基类 (DBContext) 没有接受字符串的构造函数的错误。

有什么想法吗?

请您参考如下方法:

DbContext没有这个构造函数了。您可以在 OnConfiguring 方法重载中指定连接字符串:

public class BloggingContext : DbContext 
{ 
    public DbSet<Blog> Blogs { get; set; } 
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    {          
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"); 
 
    } 
} 

https://ef.readthedocs.org/en/latest/getting-started/full-dotnet/new-db.html

UseSqlServer 是一个 extension method对于 DbContextOptionsBuilder