EF6从MySQL表中选择

时间:2019-05-21 12:55:30

标签: mysql c#-4.0 entity-framework-6

我有一个带有表的现有MySQL数据库。我正在创建Windows服务,该服务将从MySql表Route::post('contact', 'ContactController@store')->name('contact.store'); Route::post('contact', 'ContactController@company')->name('contact.company'); 中获取数据,并将该值传递给我的DTO类。

下面是我的选择语句

c2b2_callbacks

下面是我的public async Task<IEnumerable<Callback>> GetCallbacks() { using(MySqlConnection conn = new MySqlConnection(connectionString)) { try { await conn.OpenAsync(); //MySqlTransaction sqlTransaction = await conn.BeginTransactionAsync(); using (M2AContext context = new M2AContext()) { //context.Database.UseTransaction(sqlTransaction); // Error IEnumerable<CallBack> transactions = await context.Transactions.SqlQuery("SELECT * FROM oapi_test.c2b2_callbacks WHERE Status = 0 AND MSISDN REGEXP \'^([a-z]*[a-z]\\s*){3}([0-9]*[0-9]){3}([a-z]){1}$\';").ToListAsync(); return transactions; } } catch(Exception e) { //log Console.WriteLine($"Error {e.Message}"); return null; } } }

CallBack

下面是我的上下文

 public class CallBack
{
    public string TransID { get; set; }
    public DateTime TransTime { get; set; }
    public string MSISDN { get; set; }

    public Int16 Status { get; set; }
}

我正在尝试获取交易,但在[DbConfigurationType(typeof(MySqlEFConfiguration))] public class M2AContext: DbContext { public M2AContext(): base() { } public M2AContext(DbConnection connection, bool ownedconnection): base(connection, ownedconnection) { } public DbSet<Callbacks> Transactions { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } 语句中失败,并引发此错误

SELECT

我已经阅读了this文档,但不知道为什么会出现此错误。

这是堆栈跟踪

{"Object reference not set to an instance of an object."}  

1 个答案:

答案 0 :(得分:1)

我认为您需要提供一个映射,否则EF不会知道如何绑定到CallBack对象

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

应该是

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<CallBack>("c2b2_callbacks");
    }