【发布时间】:2019-11-03 05:46:29
【问题描述】:
我正在尝试在 MySQL 数据库和 Visual Studio 中的 c# 对象之间建立 ORM
我已安装以下软件包以将 MySQL 数据库添加到数据源列表:
- 连接器/NET 8.0.16:https://dev.mysql.com/downloads/connector/net/
- 适用于 Visual Studio 1.2.8 的 MySQL:https://dev.mysql.com/downloads/windows/visualstudio/
遵循这篇文章中的建议:How to connect to a MySQL Data Source in Visual Studio
我已经创建了数据源,我的代码看起来像这样......
app.config 中的连接字符串:
<connectionStrings>
<add name="MyMapper.Properties.Settings.myConnectionString" connectionString="server=my-db-instance.xxxxxxxxxxxx.eu-west-1.rds.amazonaws.com;user id=my_user_id;password=my_user_password;persistsecurityinfo=True;database=my_database" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
MyDataContext.cs 中的数据上下文:
namespace MyMapper
{
[Database]
public class MyDataContext : DataContext
{
public MyDataContext() : base(Properties.Settings.Default.myConnectionString) { }
public Table<ElementId> ElementIds;
}
}
ElementId.cs 中的映射类:
namespace MyMapper
{
[Table(Name = "ElementId")]
public class ElementId
{
[Column(Name = "IntegerValue", IsPrimaryKey = true)]
public int IntegerValue { get; set; }
}
}
在 MyController.cs 中插入操作:
ElementId my_element_id = new ElementId();
my_element_id.IntegerValue(88);
using (MyDataContext my_data_context = new MyDataContext())
{
my_data_context.ElementIds.InsertOnSubmit(my_element_id);
my_data_context.SubmitChanges();
}
执行 SubmitChanges() 时抛出以下异常:
System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server
看来问题出在与数据库的连接上
更新回答Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"? 中提出的解决方案:我不是在尝试连接到 SqlConnection 而是连接到 MySqlConnection
【问题讨论】:
-
看起来你使用的是 SqlConnection 而不是 MySqlConnection
-
@SᴇM 我没有尝试连接到 SqlConnection 而是连接到 MySqlConnection
-
@Chetan Ranpariya 是对的,这是导致异常的原因
标签: c# mysql .net entity-framework