C#实体框架:不支持关键字:“端口" [英] C# Entity Framework: Keyword not supported: 'port'

查看:154
本文介绍了C#实体框架:不支持关键字:“端口"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有多个项目连接到特定数据库,即CodeFirst Entity Framework.

Hello I have more than one project connecting to a certain DB that is CodeFirst Entity Framework.

除一个顽固的项目外,所有项目都能够成功连接.

All Projects are able to connect successfully except for one stubborn one.

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

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

I have looked through countless stackoverflow questions, mysql forums, entity framework forums etc. including:

MappingException Edm.String与SqlServer.varbinary不兼容

MySQL的连接字符串中不支持的关键字

不支持的关键字:元数据" + MySQL

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

My connection string looks like: server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

我的db.cs文件如下:

My db.cs file looks like:

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

When I remove the port:3306 from the connection string I get this: 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 Connector,而不是Sql Server ...

I am using MySql Connector and not Sql Server...

我以及我团队的其他成员对此深感困惑.

I am completely stumped by this as well as the rest of my team.

这是我的Web.Config

Here is my 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>

<?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>

推荐答案

使用的基数的参数DbContext 构造函数称为nameOrConnectionString.因此,它支持配置文件中的连接字符串的名称,或者像您实际的情况一样支持实际的连接字符串.

The argument of the used base DbContext constructor is called nameOrConnectionString. Hence it supports a name of a connection string from the configuration file, or like in your case an actual connection string.

后者的问题在于,它不允许指定提供商名称,就像前者来自配置一样,在这种情况下,EF使用defaultConnectionFactory配置元素中指定的名称,在您的情况下为System.Data.Entity.Infrastructure.SqlConnectionFactory,即 Sql Server ,因此是port不支持的异常.

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.

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

There are several ways to fix the issue.

(A)更改defaultConnectionFactory配置:

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

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

(B) Use named configuration connection string and specify explicitly the provider:

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

并将构造函数更改为

public MyDB()
{
    // ...
}

,或者该名称与您的DbContext派生类名称不同:

or if the name is different than your DbContext derived class name:

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

(C)使用 DbConfigurationTypeAttribute :

(C) Use DbConfigurationTypeAttribute:

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

这篇关于C#实体框架:不支持关键字:“端口"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆