简体   繁体   English

C# 实体框架:不支持关键字:“端口”

[英]C# Entity Framework: Keyword not supported: 'port'

Hello I have more than one project connecting to a certain DB that is CodeFirst Entity Framework.您好,我有多个项目连接到某个数据库,即 CodeFirst 实体框架。

All Projects are able to connect successfully except for one stubborn one.除了一个顽固的项目外,所有项目都能够成功连接。

The error I am getting is: Keyword not supported: 'port'我得到的错误是: Keyword not supported: 'port'

I have looked through countless stackoverflow questions, mysql forums, entity framework forums etc. including:我浏览了无数的 stackoverflow 问题、mysql 论坛、实体框架论坛等,包括:

MappingException Edm.String not compatible with SqlServer.varbinary MappingException Edm.String 与 SqlServer.varbinary 不兼容

Keyword not supported in MySQL's connection string MySQL的连接字符串中不支持关键字

Keyword not supported: 'metadata' + MySQL 不支持关键字:“元数据”+ MySQL

My connection string looks like: server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123我的连接字符串如下所示: server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

My db.cs file looks like:我的 db.cs 文件如下所示:

public partial class MyDB : DbContext
{
    public MyDB ()
        : base("server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123")
    {
        Logger.Trace("test123");
    }

    public virtual DbSet<MyItem> MyItems { 
get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyItem>()
            .Property(e => e.Content)
            .IsUnicode(false);
    }
}

When I remove the port:3306 from the connection string I get this:当我从连接字符串中删除port:3306时,我得到以下信息:

System.Data.Entity.Core.MappingException: Schema specified is not valid. Errors: 
(8,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.DateTime[Nullable=False,DefaultValue=,Precision=]' of member 'Time' in type 'something.Model.MyItem' is not compatible with 'SqlServer.timestamp[Nullable=False,DefaultValue=,MaxLength=8,FixedLength=True,StoreGeneratedPattern=Identity]' of member 'time' in type 'CodeFirstDatabaseSchema.MyItem'.
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths, Boolean throwOnError)
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders)
   at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToStorageMappingItemCollection(DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection, StoreItemCollection storeItemCollection)
   at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToMetadataWorkspace(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.Internal.CodeFirstCachedMetadataWorkspace..ctor(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.Infrastructure.DbCompiledModel..ctor(DbModel model)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at MyFunction(Int32 userId, String id, String type, String contentJsonString) in 

I am using MySql Connector and not Sql Server...我正在使用 MySql 连接器而不是 Sql 服务器...

I am completely stumped by this as well as the rest of my team.我完全被这个以及我团队的 rest 难住了。

Edit: Here is my Web.Config编辑:这是我的 Web.Config

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
      </configSections>
      <appSettings file="config-sources\app-settings.config"/>
      <system.web>
        <compilation debug="true" targetFramework="4.5.2">
          <assemblies>
            <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          </assemblies>
        </compilation>
        <httpRuntime targetFramework="4.5.1"/>
      </system.web>
      <connectionStrings configSource="config-sources\ef-connection-strings.config"/>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="MySql.Data" publicKeyToken="C5687FC88969C44D" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.8.3.0" newVersion="6.8.3.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,          MySql.Data.Entity.EF6" />
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
      <system.webServer>
        <handlers>
          <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="POST,HEAD,GET" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <security>
          <requestFiltering>
            <verbs>
              <add verb="POST" allowed="true"/>
            </verbs>
          </requestFiltering>
        </security>
        <defaultDocument>
          <files>
            <add value="webhook.ashx"/>
          </files>
        </defaultDocument>
      </system.webServer>
    </configuration> 

The argument of the used base DbContext constructor is called nameOrConnectionString .使用的基本DbContext 构造函数的参数称为nameOrConnectionString Hence it supports a name of a connection string from the configuration file, or like in your case an actual connection string.因此,它支持来自配置文件的连接字符串的名称,或者在您的情况下支持实际的连接字符串。

The problem with the later is that it doesn't allow specifying the provider name as with the former coming from the configuration, in which case EF uses the one specified in the defaultConnectionFactory configuration element, which in your case is System.Data.Entity.Infrastructure.SqlConnectionFactory , in other words - Sql Server , hence the port not supported exception.后者的问题在于它不允许指定提供者名称,因为前者来自配置,在这种情况下,EF 使用defaultConnectionFactory配置元素中指定的名称,在您的情况下是System.Data.Entity.Infrastructure.SqlConnectionFactory ,换句话说 - Sql Server ,因此port不支持异常。

There are several ways to fix the issue.有多种方法可以解决此问题。

(A) Change the defaultConnectionFactory configuration: (A) 更改defaultConnectionFactory配置:

<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"></defaultConnectionFactory>

(B) Use named configuration connection string and specify explicitly the provider: (B) 使用命名配置连接字符串并明确指定提供者:

<connectionStrings>
    <add name="MyDB" providerName="MySql.Data.MySqlClient" connectionString="server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123" />
</connectionStrings>

and change the constructor to并将构造函数更改为

public MyDB()
{
    // ...
}

or if the name is different than your DbContext derived class name:或者如果名称与您的DbContext派生类名称不同:

public MyDB() : base(connection_string_name)
{
    // ...
}

(C) Use DbConfigurationTypeAttribute : (C) 使用DbConfigurationTypeAttribute

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MyDB : DbContext
{
    // ...
}

I had this problem whilst developing a Web Application on Core 2. I had to change the default database connection used from SqlServer to MySql in the Startup.cs file where the application is configured.我在 Core 2 上开发 Web 应用程序时遇到了这个问题。我必须在配置应用程序的 Startup.cs 文件中将使用的默认数据库连接从 SqlServer 更改为 MySql。

在此处输入图片说明

The error similar to the one listed above comes while working with ASP.net core and Database.使用 ASP.net 核心和数据库时会出现类似于上面列出的错误。 The default database Provider with the ASP.net core is the SQL Server but, in case you are using a different provider for example, PostgreSQL and didn't correctly write or configure the DBContext code in the startup.cs带有 ASP.net 核心的默认数据库提供程序是 SQL Server,但是,如果您使用不同的提供程序,例如 PostgreSQL,并且没有在 startup.cs 中正确编写或配置 DBContext 代码

For example - Following code is written with an intent to connect to PostgresSQL then it will result in error ArgumentException: Keyword not supported: 'port'.例如 - 下面的代码是为了连接到 PostgresSQL 而编写的,那么它将导致错误ArgumentException: Keyword not supported: 'port'。

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   var connection = @"Server=localhost;Port=5432;Database=NewDB;User Id=xxxxx;Password=cr@aaaa;";
   services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

    // ...

}

And the reasons is user is trying to connect to PostgreSQL but did change the default Option UseSQLServer after configuring the PostgreSQL string.原因是用户试图连接到 PostgreSQL,但在配置 PostgreSQL 字符串后确实更改了默认选项 UseSQLServer。

To fix the issue change the option要解决此问题,请更改选项


options.UseSqlServer(connection)) -> options.UseNpgsql(connection)) options.UseSqlServer(connection)) -> options.UseNpgsql(connection))


I definitively solved the problem using the MySql Connector 8.0.x and following instructions on this link: https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken .我最终使用 MySql Connector 8.0.x 并按照此链接上的说明解决了该问题: https : //davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken

in details:详情:

  1. Install MySql.Data.EntityFramework.安装 MySql.Data.EntityFramework。 Do not install Install MySql.Data.Entity!不要安装安装MySql.Data.Entity!

  2. Configure web.config / app.config in this way:以这种方式配置 web.config/app.config:

    2.1. 2.1. Change the <entityFramework> tag to <entityFramework codeConfigurationType="MySql.Data.EntityFramework.MySqlEFConfiguration, MySql.Data.EntityFramework"><entityFramework>标记更改为<entityFramework codeConfigurationType="MySql.Data.EntityFramework.MySqlEFConfiguration, MySql.Data.EntityFramework">

    2.2. 2.2. Add/change the provider.添加/更改提供程序。 It has to be: <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />它必须是: <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />

    2.3. 2.3. Connection string now can be server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123连接字符串现在可以是server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

  3. Open your DbContext's configuration class (if presente) and place the following code in it's constructor: SetSqlGenerator("MySql.Data.MySqlClient" new MySql.Data.EntityFramework.MySqlMigrationSqlGenerator());打开您的 DbContext 的配置类(如果存在)并将以下代码放入其构造函数中: SetSqlGenerator("MySql.Data.MySqlClient" new MySql.Data.EntityFramework.MySqlMigrationSqlGenerator());

Sometimes it's the simplest thing.有时这是最简单的事情。 Mine was a copy-paste error when I missed the "Server=" at the beginning of the connection string.当我错过了连接字符串开头的“Server=”时,我的就是复制粘贴错误。

In my case, connection string with explicit port has to be delimited by , .在我的情况下,具有显式端口的连接字符串必须由,分隔。

Eg: Data Source=123.45.123.45,1433;...例如: Data Source=123.45.123.45,1433;...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# 实体框架中使用 sql 连接字符串中的端口:不支持关键字:“端口” - Using port in sql connection string in C# Entity Framework: Keyword not supported: 'port' “不支持关键字” MySQL C# - “Keyword not supported” MySQL C# C#实体框架查询存储过程错误“不支持文化” - C# entity framework Querying stored procedure error “Culture is not supported” 如何为C#修复此关键字不受支持的“提供商”? - How to fix this Keyword not supported “provider” for C#? C#MySQL错误:不支持关键字 - C# MySQL Error: Keyword not supported 实体框架错误不支持关键字:provider \\ r \\ nconnection string - Entity Framework error Keyword not supported: provider \r\nconnection string 不支持关键字:ASP.net Entity Framework 6中的“数据源” - Keyword not supported: 'data source' in ASP.net Entity Framework 6 实体框架4.3 Windows Azure关键字不受支持:“元数据” - Entity Framework 4.3 Windows Azure Keyword not supported: 'metadata' 实体框架核心SQLite连接字符串关键字不受支持:版本 - Entity Framework Core SQLite Connection String Keyword not supported: version 实体框架核心,不支持关键字:'server:(localdb)\mssqllocaldb;database' - Entity framework core, Keyword not supported: 'server:(localdb)\mssqllocaldb;database'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM