C# 使用DbContext拒绝访问(DbConnection,bool)
我试图使用构造函数C# 使用DbContext拒绝访问(DbConnection,bool),c#,mysql,entity-framework-6,C#,Mysql,Entity Framework 6,我试图使用构造函数DbContext(DbConnection,bool)初始化一个DbContext,但是抛出了一个异常 我使用的是MySQLV5.7.9,Connector/NET6.9.8 为了澄清,我能够使用MySqlCommand成功地连接和查询数据库 using (var connection = Database.Connect()) { using (MySqlCommand command = connection.Cre
DbContext(DbConnection,bool)
初始化一个DbContext
,但是抛出了一个异常
我使用的是MySQLV5.7.9,Connector/NET6.9.8
为了澄清,我能够使用MySqlCommand
成功地连接和查询数据库
using (var connection = Database.Connect())
{
using (MySqlCommand command = connection.CreateCommand())
{
command.CommandText = @"SELECT * FROM `database`.`table`";
command.Prepare();
using (IDataReader reader = command.ExecuteReader())
{
List<StateObject> items = new List<object>();
while (reader.Read())
{
incidents.Add(new StateObject(reader));
}
Items = new ObservableCollection<StateObject>(items);
}
}
}
从我看到的情况来看,尽管我传递了一个DbConnection对象,DbContext还是在构建一个全新的连接,并且只猜测连接字符串的一部分
我是不是用错了这个构造函数
DbContext
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class IncidentContext : DbContext
{
public DbSet<IncidentModel> Incidents { get; set; }
public IncidentContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
}
这样使用:
public void GetIncident()
{
using (var context = new IncidentContext(Database.GetConnection(), true))
{
var completeIncident = context.Incidents.FirstOrDefault(incident => incident.IncidentID == Current.IncidentID);
}
}
数据库静态类
public static MySqlConnection Connect()
{
try
{
var c = new MySqlConnection("server=localhost;uid=username;pwd=password;database=database;port=3306;");
c.Open();
return c;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
如例外情况所述,您的用户无权连接到数据库,请更改您的连接字符串(user和pwd),并检查此用户是否有权访问数据库中的do crud我的连接字符串是否有密码。异常声明未使用密码。my App.config中的连接字符串也有密码。我不知道连接字符串是从哪里来的。作为测试,我从App.config中删除了连接字符串,错误仍然存在。@user2210050可能是因为您使用的用户可以本地访问它,但不能远程访问,而您试图从运行数据库的机器以外的机器访问它?然后,您必须将权限添加到数据库中。@Prix我可以使用给定的连接字符串进行选择,并且可以使用
DbContext(connectionString)
和使用EF检索记录。
public void GetIncident()
{
using (var context = new IncidentContext(Database.GetConnection(), true))
{
var completeIncident = context.Incidents.FirstOrDefault(incident => incident.IncidentID == Current.IncidentID);
}
}
public static MySqlConnection Connect()
{
try
{
var c = new MySqlConnection("server=localhost;uid=username;pwd=password;database=database;port=3306;");
c.Open();
return c;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}