【问题标题】:dotnet-core ef sql connectiondotnet-core ef sql 连接
【发布时间】:2017-07-04 16:47:33
【问题描述】:

我想设置 sql 连接到 config.json 并从 AuditContext 类中使用它。 但是当我从 PMC 运行示例 drop-database 时,我得到一个错误。

System.ArgumentException:初始化字符串的格式不符合从索引 21 开始的规范。 在 System.Data.Common.DbConnectionOptions.GetKeyValuePair(字符串 connectionString,Int32 currentPosition,StringBuilder 缓冲区,字符串和键名,字符串和键值) 在 System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 同义词) 在 System.Data.Common.DbConnectionOptions..ctor(字符串 connectionString,Dictionary2 synonyms) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection() at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value() 在 Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.GetContextInfo(字符串 contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.GetContextInfoImpl(字符串 contextType) 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0() 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action 动作)

这是我的 Startup.cs 类

using System.Threading.Tasks;
using Audit.Models.Entity;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace Audit
{
public class Startup
{
    private IHostingEnvironment _env;
    private IConfigurationRoot _config;

    public Startup(IHostingEnvironment env)
    {
        _env = env;

        var builder = new ConfigurationBuilder()
            .SetBasePath(_env.ContentRootPath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();

        _config = builder.Build();
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(_config);

        services.AddDbContext<AuditContext>();

        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail = false;
            config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
            config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = async ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                    await Task.Yield();

                }
            };
        }).AddEntityFrameworkStores<AuditContext>();

        services.AddLogging();

        services.AddMvc()
            .AddJsonOptions(config =>
                {
                    config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            loggerFactory.AddDebug(LogLevel.Information);
        }
        else
        {
            loggerFactory.AddDebug(LogLevel.Error);
        }

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseMvc(config =>
        {
            config.MapRoute(
              name: "Default",
              template: "{controller}/{action}/{id?}",
              defaults: new { controller = "App", action = "Index" }
              );
        });
    }
  }
  }

这里是 config.json

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}

这里是 AuditContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace Audit.Models.Entity
{
    public class AuditContext : IdentityDbContext<ApplicationUser>
    {
        private IConfigurationRoot _config;

        public AuditContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }

        public DbSet<Aql> Aql { get; set; }
        public DbSet<AqlVer> AqlVer { get; set; }
        public DbSet<Cartiglio> Cartiglio { get; set; }
        public DbSet<CartonBox> CartonBox { get; set; }
        public DbSet<CartonBoxLog> CartonBoxLog { get; set; }
        public DbSet<Entry> Entry { get; set; }
        public DbSet<Fashion> Fashion { get; set; }
        public DbSet<Level> Level { get; set; }
        public DbSet<MasterCode> MasterCode { get; set; }
        public DbSet<Settings> Settings { get; set; }
        public DbSet<SubCode> SubCode { get; set; }
        public DbSet<TotalProduction> TotalProduction { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:AuditDbContextConnection"]);
        }


    }

}

我做错了什么,在哪里? 谢谢。

【问题讨论】:

  • 我认为在“数据库”、“用户 ID”和“密码”之后的连接字符串中,您需要“=”而不是“:”。我确定 '=' 是有效的,我从来没有见过 ':' 那里,我猜那是无效的。
  • ROFL,我真的很怀念。我看了 100 次那部分,我没有注意到...
  • 是的,我知道这一点,我想每个人都会遇到这种情况……这就是为什么向其他人展示它是件好事。 ;)。使用 '=' 进行修复有帮助吗?

标签: .net-core entity-framework-core


【解决方案1】:

因此,正如 cmets 中所讨论的,问题在于连接字符串包含 ':' 而不是 '='。

所以代替:

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}

这样就可以了:

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database=databasename;User Id=user;Password=password;"
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多