Unable to call stored procedure with FromSql in EF Core

谁都会走 提交于 2019-12-11 08:48:30

问题


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:


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



来源:https://stackoverflow.com/questions/42500832/unable-to-call-stored-procedure-with-fromsql-in-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!