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

编程入门 行业动态 更新时间:2024-10-26 22:28:22
本文介绍了无法在EF Core中使用FromSql调用存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从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.

类:

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; } }

查询:

_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 });

例外情况:

抛出异常: Microsoft.EntityFrameworkCore.dll中的'System.InvalidOperationException'

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

其他信息:无法创建'PlayerOverview'的DbSet,因为此类型不包含在上下文模型中。

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

如何包含此类型类在上下文中的模型?如果我添加 DbSet< PlayerOverview> ,则会收到另一个异常,抱怨该集合缺少主键。

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并定义一个主键,因为没有名为Id或PalyerOverviewId的列,EF无法猜测哪个列是键。因此,请使用[Key]属性或流利的api(或仅在结果和模型中添加唯一的PlayerOverviewId:

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; }

docs.microsoft/en-us/ef/core/modeling/keys

更多推荐

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

本文发布于:2023-11-08 16:28:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存储过程   EF   Core   FromSql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!