简体   繁体   English

如何在 EF.core 中使用 FromSqlRaw 指定列

[英]How can I specific columns using FromSqlRaw in EF.core

I just used FromSqlRaw.我刚刚使用了FromSqlRaw。 In Microsoft tutorial enter link description here , using FromSqlRaw has to select all columns (pls, I haven't seen some good examples as well).在 Microsoft 教程中,在此处输入链接描述,使用 FromSqlRaw 必须到 select 所有列(请,我还没有看到一些好的示例)。 But what I want is to select some specific columns when joining several tables.但我想要的是 select 加入几个表时的一些特定列。

Firstly, I joined two tables as following shown (RequestMaterial has Request's Key as Foreign Key):首先,我加入了如下所示的两个表(RequestMaterial 将请求的键作为外键):

var requestVm = CurrentDbContext.PmrRequest
                .FromSqlRaw("Select [r].[RequestName] from [Request] as [r] " +
                            "LEFT JOIN [RequestMaterial] as [m] On [r].RequestId = [m].RequestId " +
                            "where [r].[InitiatorUserId] = 'xxxx'")
                            .ToList();

The error message is "The underlying reader doesn't have as many fields as expected".错误消息是“底层阅读器没有预期的那么多字段”。

When I tried to select a column without joining tables like:当我尝试 select 列而不连接表时,例如:

var requestVm = CurrentDbContext.PmrRequest
                .FromSqlRaw("Select [r].[RequestName] from [Request] as [r] " +
                            "where [r].[InitiatorUserId] = 'xxxx'")
                            .ToList();

The same error is reported.报告相同的错误。 Up to now, this problem can only be fixed when I select all columns.到目前为止,这个问题只能在我 select 的所有列时修复。 But the question is when I did this with joining tables, duplicated columns (RequestId) are selected with error reported ("An item with the same key has already been added. Key: RequestId'").但问题是,当我使用连接表执行此操作时,选择了重复的列(RequestId)并报告了错误(“已添加具有相同键的项目。键:RequestId'”)。

Does Anyone have similar experiences?有没有人有类似的经历? Or Any solutions for the mentioned condition?或上述情况的任何解决方案?

Create a special class to get data from sp.创建一个特殊的 class 从 sp 获取数据。 This class should have all properties that select of store procedure has.这个 class 应该具有存储过程的 select 具有的所有属性。 You don't need to select everytning.您不需要 select 每一天。 Just select what you need.只需 select 您需要什么。

public class ResultData
{
public string RequestName {get;set;}
public string RequestMaterial {get;set;}
.....
.....
}

after this add to dbContext DbSet and config no key like this在此之后添加到 dbContext DbSet 并配置没有这样的键

modelBuilder.Entity<ResultData>(e =>
        {
            e.HasNoKey();
        });

And this a sample function to get data using the store procedure这是一个示例 function 使用存储过程获取数据


public async Task<IEnumerable<ResultData>> GetDetailsData(int id, string name)
{
    var pId = new SqlParameter("@InitiatorUserId", id);
 
    return await _context.Set<ResultData>()
             .FromSqlRaw("Execute sp_GetData  @Id ", parameters: new[] { pId })
            .ToArrayAsync();
}

if you use ef core less then 3.0, use.FromSql instead of.FromSqlRaw如果你使用低于 3.0 的 ef core,使用 .FromSql 而不是 .FromSqlRaw

The DbSet must be included in the model (ie it can not be configured as Ignored). DbSet 必须包含在 model 中(即不能配置为忽略)。 All columns in the target table that map to properties on the entity must be included in the SQL statement. map 到实体上的属性的目标表中的所有列必须包含在 SQL 语句中。 The column names must match those that the properties are mapped to.列名必须与属性映射到的那些匹配。 Property names are not taken into account when the results are hydrated into instances of the entity.当结果被水合到实体的实例中时,不考虑属性名称。

If any columns are missing, or are returned with names not mapped to properties, an InvalidOperationException will be raised with the message:如果缺少任何列,或者返回的名称未映射到属性,则会引发 InvalidOperationException 并显示以下消息:

'The required column '[name of first missing column]' was not present in the results of a 'FromSqlRaw' operation.' 'FromSqlRaw' 操作的结果中不存在所需的列'[第一个缺失列的名称]'。

Sorry, when I read the official tutiral, I found this抱歉,当我阅读官方教程时,我发现了这个

There are a few limitations to be aware of when using raw SQL queries:使用原始 SQL 查询时需要注意一些限制:

The SQL query must return data for all properties of the entity type. SQL 查询必须返回实体类型的所有属性的数据。

Therefore, currently, we are not allowed to specify columns using FromSqlRaw in EF.core 2.0+.因此,目前,我们不允许在 EF.core 2.0+ 中使用 FromSqlRaw 指定列。

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

相关问题 如何在 EF.Core 5 中添加具有相同外键的多个导航属性? - How can I add multiple navigation properties with the same Foreign Key in EF.Core 5? 如何在LINQ或EF.Core中执行此操作? - How to do this in LINQ or EF.Core? 如何使用 EF.Core Database First 包含特殊字符 $ 脚手架表 - How do I Scaffold tables with EF.Core Database First containing special characters $ 如何从 EF Core 的 FromSqlRaw 获取空间值 - How do I get a spatial value from EF Core's FromSqlRaw 带有列变量的 EF Core FromSqlRaw - EF Core FromSqlRaw with column variable 如何通过 FromSqlRaw 在 EF Core 3.0 中调用存储过程 - How to call a stored procedure in EF Core 3.0 via FromSqlRaw 如何在 FromSqlRaw 上异步调用 FirstOrDefault? - How can I call FirstOrDefault on FromSqlRaw asynchronously? 使用 Code First 和 EF.Core 引用表以进行有效搜索的正确方法是什么 - What's the correct way to reference tables using Code First with EF.Core for searching efficiently EF Core FromSQLRaw 和存储过程插入数据 - EF Core FromSQLRaw and Stored Procedures to insert data .NET Core 3 / EF.Core 3:`QueryModelGenerator`、`RelationalQueryModelVisitor` 等发生了什么 - .NET Core 3 / EF.Core 3: what happened to `QueryModelGenerator`, `RelationalQueryModelVisitor` and etc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM