简体   繁体   English

无法使用EF Core中的FromSql调用存储过程

[英]Unable to call stored procedure with FromSql in EF Core

I am trying to call a stored procedure from EF Core, and am running into an error I don't know how to solve. 我试图从EF Core调用存储过程,并遇到错误,我不知道如何解决。

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 抛出异常:Microsoft.EntityFrameworkCore.dll中的“System.InvalidOperationException”

Additional information: Cannot create a DbSet for 'PlayerOverview' because this type is not included in the model for the context. 附加信息:无法为“PlayerOverview”创建DbSet,因为此类型未包含在上下文的模型中。

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. 如果我添加一个DbSet<PlayerOverview>我会得到一个不同的异常,抱怨该集合缺少主键。

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. 您需要添加DbSet并定义主键,因为没有名为Id或PalyerOverviewId的列,EF无法猜测哪个列是键。 So use either the [Key] attribute or the fluent api (or simply add a unique PlayerOverviewId to your result and model: 因此,使用[Key]属性或流畅的api(或者只是在结果和模型中添加一个唯一的PlayerOverviewId:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM