简体   繁体   中英

Entity Framework Core 2 with DBQuery - Get Object reference not set to an instance of an object

I'm using Entity Framework Core 2 and tried BDQuery. When I try to map the result of a FromSql() request in a Select , I get an error:

Object reference not set to an instance of an object.

Here is my DBContext class:

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options) { }

    public DbQuery<MyEntity> MyEntities { get; set; }
}

Here is the MyEntity class definition:

public class MyEntity
{
    public int Id { get; set;}
}

If in my code I make the following call, it works fine ( _dbContext is of type MyDbContext of course):

var result = await _dbContext.MyEntities
   .FromSql("Exec MyStoredProc")
   .Select(s => new { s.Id })
   .ToListAsync()

The MyStoredProc returns a column with name Id.

But if I declare a class MyDTO like this:

public class MyDTO
{
    public int MyId { get; set;}
}

And then make a call like this:

var result = await _dbContext.MyEntities
   .FromSql("Exec MyStoredProc")
   .Select(s => new MyDTO {MyId = s.Id })
   .ToListAsync()

Then an exception is raised:

Object reference not set to an instance of an object

If I rename the field MyId by Id in the MyDTO Class definition, it works fine again.

Any idea regarding this behavior? Why when the field name doesn't map with the SQL column name an error occurs?

Thank you

Try forcing a call to the Db. What I think is happening is Entity Framework is trying to compose upon your LINQ query and it doesn't know how to map MyId, when really we want it to make the call, and then manipulate the objects in memory.

var result = await _dbContext.MyEntities
   .FromSql("Exec MyStoredProc")
   .AsEnumerable() // <---- Try to force a call to the db. 
   .Select(s => new MyDTO {MyId = s.Id })
   .ToListAsync()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM