Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The required column 'id' was not present in the results of a `FromSql` operation

I have this entity class:

public class PoDetail
{
    [Key]
    public int Id { get; set; }
    public string ProductId { get; set; }
    public virtual Product Product { get; set; }
}

And I’m trying to run a query on it:

public IActionResult Data()
    {           
        var result = _context.PoDetail
            .FromSqlRaw("select count(ProductId) as count, ProductId from dbo.PoDetail group by ProductId").ToList();
        return Json(result);         
    }

It works fine when I run in query console.
But on the browser I am getting this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The required column ‘id’ was not present in the results of a FromSql operation

But if I include the id column in query. I won’t get the desired output.

>Solution :

You need to create a new class to hold the desired result:

public class PoSummary
{
    public int Count { get; set; }
    public string ProductId { get; set; }
}

Add it to your DbContext:

modelBuilder.Entity<PoSummary>().HasNoKey().ToView(null);

And then:

public IActionResult Data()
    {           
        var result = _context.PoSummary
            .FromSqlRaw("select count(ProductId) as count, ProductId from dbo.PoDetail group by ProductId").ToList();
        return Json(result);         
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading