我有一个.net Core应用程序,我一直在尝试使用Windows身份验证从我的本地SQL Server实例(2014)中读取并继续遇到有关我的连接字符串的重复错误。我一直在审查MSDN文档以及connectionstrings.com,并认为我已正确配置了所有内容。
这是我的错误:
“System.ArgumentException:'初始化字符串的格式不符合从索引0开始的规范。'”
我的意思是我的连接字符串的开头。
我已阅读与此确切问题相关的其他帖子,但未能使用它们来查找解决方案。
这是我在发生错误时尝试的内容:
public class HomeController : Controller
{
private ModelContext _context;
public HomeController()
{}
public IActionResult Index()
{
var viewModel = new HomeViewModel();
var optionsBuilder = new DbContextOptionsBuilder<ModelContext>();
optionsBuilder.UseSqlServer("DefaultConnection");
using (_context = new ModelContext(optionsBuilder.Options))
{
>>>>>> viewModel.List = _context.TableName.ToList(); <<<<<<<<
我在“appsettings.json”文件中有以下内容:
"ConnectionStrings": {
"DefaultConnection": "Server=MyComputerName; Database=DBName; IntegratedSecurity=SSPI;"
},
在我的“ModelContext.cs”文件中
public class ModelContext : DbContext
{
public ModelContext(DbContextOptions<ModelContext> options)
:base(options)
{ }
[<Table Properties>]
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("DefaultConnection");
}
和“Startup.cs”文件:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<ModelContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
谢谢参观!
在对EF Core DbContext的MS Documents站点进行了多次思考和重新审核之后,我发现我正在尝试实现DbContext配置的所有3种方法:构造函数参数,OnConfiguring和依赖注入。
决定使用OnConfiguring来移动应用程序。