.NET核心实体框架存储过程 [英] .NET Core Entity Framework stored procedures

查看:117
本文介绍了.NET核心实体框架存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ASP.NET 4.5应用程序移植到.NET Core,但我有一个真正的问题,我似乎无法弄清楚.

I'm trying to port a ASP.NET 4.5 application to .NET Core and I have one real issue I can't seem to figure out.

我现有的应用程序执行存储的proc,这些proc返回具有多个数据表的数据集.实体框架可以自动将返回的字段映射到我的实体属性,但(自然)仅适用于数据集中的第一个数据表.

My existing application executes stored procs which return a dataset with multiple datatables. The Entity Framework can automatically map the returned fields to my entity properties but only works with the first datatable in the dataset (naturally).

因此,我只是试图找出是否有可能以某种方式拦截模型构建过程,并使用自定义代码来处理数据集并查看其他数据表以设置实体字段.

So I'm just trying to figure out if its at all possible to somehow intercept the model building process and use custom code to process the dataset and look into the other datatables to set entity fields.

我知道我可以使用通常的方法直接通过SqlConnection执行存储过程,但是我想知道Entity Framework是否已经可以执行此操作.

I know I can use the normal way of executing the stored procedure directly using the SqlConnection but I'm wondering if the Entity Framework has some way to do this already.

推荐答案

目前,执行存储过程,返回数据将使用DbSet.FromSql方法.

At the moment, the way to execute stored procedures that return data is to use the DbSet.FromSql method.

using (var context = new SampleContext())
{
    var data= context.MyEntity
        .FromSql("EXEC GetData")
        .ToList();
}

这有一定的局限性:

  • 必须在DbSet
  • 上调用它
  • 返回的数据必须映射到DbSet类型
  • 上的所有属性
  • 它不支持临时对象.
  • It must be called on a DbSet
  • The returned data must map to all properties on the DbSet type
  • It does not support ad hoc objects.

或者您可以退回到普通的ADO.NET:

Or you can fall back to plain ADO.NET:

using (var context = new SampleContext())
using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "GetData";
    command.CommandType = CommandType.StoredProcedure;
    context.Database.OpenConnection();
    using (var result = command.ExecuteReader())
    {
        // do something with result
    }
}

计划引入支持,以从SQL查询返回临时类型,网址为某个阶段.

这篇关于.NET核心实体框架存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆