Alo*_*kai 5 .net c# mysql entity-framework
您好我有一个以上的项目连接到CodeFirst Entity Framework的某个数据库.
除了一个顽固的项目外,所有项目都能成功连接.
我得到的错误是: Keyword not supported: 'port'
我查看了无数的stackoverflow问题,mysql论坛,实体框架论坛等,包括:
MappingException Edm.String与SqlServer.varbinary不兼容
我的连接字符串如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我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 Connector而不是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>
所使用的基础的参数DbContext 的构造函数被调用nameOrConnectionString.因此,它支持配置文件中的连接字符串的名称,或者在您的情况下支持实际的连接字符串.
后者的问题是它不允许指定提供者名称,因为前者来自配置,在这种情况下,EF使用defaultConnectionFactory配置元素中指定的那个System.Data.Entity.Infrastructure.SqlConnectionFactory,换句话说就是--Sql Server因此port不受支持的例外.
有几种方法可以解决这个问题.
(A)更改defaultConnectionFactory配置:
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"></defaultConnectionFactory>
Run Code Online (Sandbox Code Playgroud)
(B)使用命名配置连接字符串并明确指定提供者:
<connectionStrings>
<add name="MyDB" providerName="MySql.Data.MySqlClient" connectionString="server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
并将构造函数更改为
public MyDB()
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者如果名称与DbContext派生类名称不同:
public MyDB() : base(connection_string_name)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
(C)使用DbConfigurationTypeAttribute:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MyDB : DbContext
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
小智 8
使用 ASP.net core 和数据库时会出现与上面列出的错误类似的错误。ASP.net core 的默认数据库提供程序是 SQL Server,但如果您使用不同的提供程序(例如 PostgreSQL)并且没有在startup.cs 中正确编写或配置 DBContext 代码
例如 - 编写以下代码的目的是连接到 PostgresSQL,然后它将导致错误ArgumentException:不支持关键字:'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));
// ...
}
Run Code Online (Sandbox Code Playgroud)
原因是用户尝试连接到 PostgreSQL,但在配置 PostgreSQL 字符串后更改了默认选项 UseSQLServer。
要解决该问题,请更改选项
选项.UseSqlServer(连接)) -> 选项.UseNpgsql(连接))
我在 Core 2 上开发 Web 应用程序时遇到了这个问题。我必须在配置应用程序的 Startup.cs 文件中将使用的默认数据库连接从 SqlServer 更改为 MySql。