【发布时间】:2016-02-11 23:12:05
【问题描述】:
我正在尝试使用构造函数 DbContext(DbConnection,bool) 初始化 DbContext,但引发了异常。
我正在使用 MySQL v5.7.9,Connector/Net 6.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);
}
}
}
例外:
System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> MySql.Data.MySqlClient.MySqlException: Authentication to host '127.0.0.1' for user 'root' using method 'mysql_native_password' failed with message: Access denied for user 'floortracker'@'localhost' (using password: NO) ---> MySql.Data.MySqlClient.MySqlException: Access denied for user 'floortracker'@'localhost' (using password: NO)
据我所知,尽管我传递了一个 DbConnection 对象,但 DbContext 仍然在构建一个全新的连接,并且只猜测连接字符串的一部分。
我是不是用错了这个构造函数?
数据库上下文
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class IncidentContext : DbContext
{
public DbSet<IncidentModel> Incidents { get; set; }
public IncidentContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
}
事件
[Table("incidents")]
public class IncidentModel : ModelBase
{
[Key]
[Column("incId")]
public int IncidentID { get; set; }
}
这样使用:
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;
}
【问题讨论】:
标签: c# mysql entity-framework-6