ami*_*133 2 c# linq sql-server entity-framework entity-framework-core
我有一个主要问题FromSql,就是这样:
我有一个这样的模型:
public partial class model
{
public string name
}
Run Code Online (Sandbox Code Playgroud)
我想从数据库中的过程中获取一些结果(sql serever)。当我执行以下代码
var sql = "EXECUTE [myprocedure] @param1 ";
SqlParameter sqlParameter = new SqlParameter
{
ParameterName = "param1",
DbType = DbType.Int32,
Value = 10;
}
var result = db.model.FromSql(sql,SqlParameter);
Run Code Online (Sandbox Code Playgroud)
它显示了这样一个例子:
The entity type 'model' requires a primary key to be defined.
所以我在模型中添加了主键:
public partial class model
{
[key]
public int ID {set;get;}
public string name
}
Run Code Online (Sandbox Code Playgroud)
但这次它显示了此执行:The required column 'ID' was not present in the results of a 'FromSql' operation.
我知道我必须添加ID到数据库响应中,但是由于我的数据库中有很多过程,所以无法进行全部编辑,因此无法执行此操作。因此,我正在寻找一种无需编辑程序即可解决问题的方法。
可以帮我吗?
如果您使用的是Entity Framework Core 2.x,请查看查询类型(https://docs.microsoft.com/zh-cn/ef/core/modeling/query-types)。表(实体类型)始终需要一个ID,而查询类型则不需要。
使用查询类型,您可以省略ID。否则,您必须确保您的存储过程也返回一个ID,因为表/实体类型始终需要一个ID。
从EF Core 3.0开始,使用.HasNoKey()而不是查询类型来定义不带ID的实体(https://docs.microsoft.com/de-de/ef/core/what-is-new/ef-core- 3.0 / breaking-changes#query-types-solid-with-entity-types)。