EFcore中的'FromSql'操作的结果中不存在所需的列'id' [英] The required column 'id' was not present in the results of a `FromSql` operation in EFcore
问题描述
我在 FromSql
上遇到了一个主要问题,就是这样:
I have a major problem with FromSql
and that's it :
我有一个这样的模型:
public partial class model
{
public string name
}
我想从数据库(sql serever)中的过程中得到一些结果.当我执行以下代码
I want to get some result from my procedure in database(sql serever). when I execute below code
var sql = "EXECUTE [myprocedure] @param1 ";
SqlParameter sqlParameter = new SqlParameter
{
ParameterName = "param1",
DbType = DbType.Int32,
Value = 10;
}
var result = db.model.FromSql(sql,SqlParameter);
它显示了这样一个例外:实体类型模型"要求定义主键.
因此,我向模型添加了主键:
it show an exeption like this:
The entity type 'model' requires a primary key to be defined.
So I add primary key to my model:
public partial class model
{
[key]
public int ID {set;get;}
public string name
}
但是这一次它显示了此执行:'FromSql'操作的结果中没有所需的列'ID'.
But in this time it shows this execption :The required column 'ID' was not present in the results of a 'FromSql' operation.
我知道我必须在数据库响应中添加 ID
,但是由于我的数据库中有很多程序,所以我无法全部编辑,因此无法执行此操作.因此,我正在寻找一种无需编辑程序即可解决问题的方法.
I know I must add ID
to my Database response but I can't do this beacuse I have a lot of procedure in my Database so I can't edit all of them.
So I am looking for a method to solve my problem without editing my procedures.
能帮上我吗?!
推荐答案
如果您使用的是Entity Framework Core 2.x,请查看查询类型(
If you are using Entity Framework Core 2.x take a look at Query Types (https://docs.microsoft.com/en-us/ef/core/modeling/query-types). Tables (entity types) always need an ID, query types do not.
使用查询类型,您可以省略ID.否则,您必须确保您的存储过程也返回一个ID,因为表/实体类型始终需要一个ID.
With query types you can omit the ID. Otherwise you have to make sure that your stored procedure also returns an ID since table/entity types always need one.
从EF Core 3.0开始,使用.HasNoKey()而不是查询类型来定义不带ID的实体(
Starting with EF Core 3.0 there is a .HasNoKey() instead of query types to define entities without ID (https://docs.microsoft.com/de-de/ef/core/what-is-new/ef-core-3.0/breaking-changes#query-types-are-consolidated-with-entity-types).
这篇关于EFcore中的'FromSql'操作的结果中不存在所需的列'id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!