【问题标题】:C# Entity Framework: Keyword not supported: 'port'C# 实体框架:不支持关键字:“端口”
【发布时间】:2017-12-26 07:05:54
【问题描述】:

您好,我有多个项目连接到某个数据库,即 CodeFirst 实体框架。

所有项目都能成功连接,除了一个顽固的项目。

我得到的错误是:Keyword not supported: 'port'

我浏览了无数的stackoverflow问题、mysql论坛、实体框架论坛等,包括:

MappingException Edm.String not compatible with SqlServer.varbinary

Keyword not supported in MySQL's connection string

Keyword not supported: 'metadata' + MySQL

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

我的 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);
    }
}

当我从连接字符串中删除 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 

我使用的是 MySql 连接器而不是 Sql Server...

我和我团队的其他成员都被这件事难住了。

编辑: 这是我的 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> 

【问题讨论】:

  • 您的端口号不是问题。你不能那样指定它,但除非你更改了 Mysql 默认端口,否则你不应该这样做。
  • 也许这与您遇到的问题相同 => stackoverflow.com/questions/12186044/…
  • 你能发布配置文件的相关部分吗? port 异常表示 EF 正在尝试连接到 Sql Server。
  • @NormTheThird,我对此进行了调查,即使将 DateTime 更改为 TimeSpan 后,我仍然会遇到同样的错误。真正奇怪的是,错误是在谈论我没有使用也不想使用的 SqlServer!

标签: c# mysql .net entity-framework


【解决方案1】:

使用的基础DbContext constructor 的参数称为nameOrConnectionString。因此,它支持来自配置文件的连接字符串的名称,或者在您的情况下支持实际的连接字符串。

后者的问题是它不允许像前者一样从配置中指定 provider name,在这种情况下,EF 使用 defaultConnectionFactory 配置元素中指定的那个,在您的情况下是 System.Data.Entity.Infrastructure.SqlConnectionFactory,换句话说 - Sql Server,因此 port 不支持异常。

有几种方法可以解决此问题。

(A) 更改defaultConnectionFactory 配置:

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

(B) 使用命名配置连接字符串并明确指定提供者:

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

并将构造函数更改为

public MyDB()
{
    // ...
}

或者如果名称与您的 DbContext 派生类名称不同:

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

(C) 使用DbConfigurationTypeAttribute:

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

【讨论】:

  • 非常感谢!我最终使用了选项 (A),尽管我想使用选项 (C) 我无法从任何地方导入 MySql.Data.Entity... 可能需要为此更新我的 MySqlConnector 版本
  • 我应该把(A)解决方案放在哪里?在 csproj 中?
  • @HaikalNashuha (A) 用于 App.config(或 Web.config)文件
【解决方案2】:

我在 Core 2 上开发 Web 应用程序时遇到了这个问题。我必须在配置应用程序的 Startup.cs 文件中将使用的默认数据库连接从 SqlServer 更改为 MySql。

【讨论】:

    【解决方案3】:

    使用 ASP.net 核心和数据库时出现类似于上面列出的错误。具有 ASP.net 核心的默认数据库提供程序是 SQL Server,但如果您使用不同的提供程序,例如 PostgreSQL,并且没有在 startup.cs 中正确编写或配置 DBContext 代码

    例如 - 以下代码是为了连接到 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));
    
        // ...
    
    }
    

    原因是用户尝试连接到 PostgreSQL,但在配置 PostgreSQL 字符串后更改了默认选项 UseSQLServer。

    要解决问题,请更改选项


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


    【讨论】:

      【解决方案4】:

      我使用 MySql 连接器 8.0.x 并按照此链接上的说明明确解决了该问题:https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken

      详细说明:

      1. 安装 MySql.Data.EntityFramework。不要安装安装 MySql.Data.Entity!

      2. 这样配置web.config/app.config:

        2.1。将&lt;entityFramework&gt;标签改为&lt;entityFramework codeConfigurationType="MySql.Data.EntityFramework.MySqlEFConfiguration, MySql.Data.EntityFramework"&gt;

        2.2。添加/更改提供程序。必须是:&lt;provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" /&gt;

        2.3。连接字符串现在可以是server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

      3. 打开 DbContext 的配置类(如果存在)并将以下代码放入它的构造函数中: SetSqlGenerator("MySql.Data.MySqlClient" new MySql.Data.EntityFramework.MySqlMigrationSqlGenerator());

      【讨论】:

        【解决方案5】:

        有时这是最简单的事情。当我错过了连接字符串开头的“Server=”时,我的是一个复制粘贴错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-07
          • 1970-01-01
          • 1970-01-01
          • 2019-02-09
          • 2011-09-06
          • 1970-01-01
          • 2011-10-23
          • 1970-01-01
          相关资源
          最近更新 更多