Hello Anjali Agarwal,
You’re hitting “The required column 'ID' was not present …” because EF Core needs the result set columns to line up with the entity it’s materializing, and there are a couple of pitfalls in your sample:
- The entity class name
Typeclashes withSystem.Type. Rename it. - The data annotation is
[Key](capital K), not[key]. - When using
FromSqlRawfor an entity type, ensure the stored procedure returns column names that EF can bind to the entity’s properties. The safest route is to alias the columns to your CLR property names, or use[Column(...)]and still ensure the proc returns correspondingly named columns.
My recommendations:
- Rename the entity and fix annotations
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class FormType
{
[Key]
[Column("ID")]
public int Id { get; set; }
[Column("Type")]
public string Name { get; set; } = string.Empty;
}
- Ensure the
DbSetexists on your context
public DbSet<FormType> FormTypes { get; set; }
- Make the stored procedure (or its final SELECT) return aliases matching CLR property names
- If you keep the CLR properties
IdandName, alias in SQL:
SELECT [ID] AS [Id], [Type] AS [Name] FROM ...
- Call the procedure via EF Core
var types = await _context.FormTypes
.FromSqlRaw("EXEC ListFormTypes")
.AsNoTracking()
.ToListAsync();
EF Core validates that the columns needed to build FormType are present. Renaming the class avoids the System.Type collision, [Key] ensures EF recognizes the primary key, and the SQL aliases guarantee column/property alignment, removing the “required column 'ID'” exception.
Hope this solves your problem.