Unable to call stored procedure with FromSql in EF Core

c# entity-framework-core

Question

I am trying to call a stored procedure from EF Core, and am running into an error I don't know how to solve.

Class:

public class PlayerOverview
{
    public string Player { get; set; }
    public int World { get; set; }
    public string Alliance { get; set; }
    public int Score { get; set; }
    public int Castles { get; set; }
    public int Cities { get; set; }
}

Query:

    _context.Set<PlayerOverview>()
            .FromSql($"CALL usp_player_overview('{player}')")
            .Select(pl => new
            {
                Player = pl.Player,
                World = pl.World,
                Alliance = pl.Alliance,
                Score = pl.Score,
                Castles = pl.Castles,
                Cities = pl.Cities
            });

The Exception:

Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll

Additional information: Cannot create a DbSet for 'PlayerOverview' because this type is not included in the model for the context.

How can I include this class in the model for the context? If I add a DbSet<PlayerOverview> I get a different exception complaining about a lack of primary key for the set.

1
1
2/28/2017 5:26:54 AM

Popular Answer

You need to add a DbSet, and define a primary key, as there are no columns called Id or PalyerOverviewId, EF is unable to guess which column is the key. So use either the [Key] attribute or the fluent api (or simply add a unique PlayerOverviewId to your result and model:

[Key]
public string Player { get; set; }

https://docs.microsoft.com/en-us/ef/core/modeling/keys

3
2/28/2017 6:21:35 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow