2

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vbond007
  • 43
  • 5

1 Answers1

2

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()
Josie G. Bigler
  • 367
  • 4
  • 14
  • Excellent. It solved the issue. But the .ToListAsync() doesn't exist, I have to use .ToList(). Thank you very much for you quick answer ! – vbond007 Nov 15 '19 at 15:43