【问题标题】:Entity Framework Core 2.0 call stored procedure [duplicate]Entity Framework Core 2.0调用存储过程[重复]
【发布时间】:2018-04-25 17:04:48
【问题描述】:

如何使用 Entity Framework Core 2.0 调用存储过程? C# 中的 Asp.net core 2.0 站点

【问题讨论】:

  • 你试过什么?例如,你试过用谷歌搜索这个吗?因为你会得到很多结果。请尝试一下,然后提出具体问题。
  • 我已经用谷歌搜索并尝试了几个选项,但大多数谷歌资料指的是实体核心 1.0 而不是 2.0,数据上下文的成员不存在。
  • 你能贴出你试过的代码并贴出你从中得到的错误信息吗
  • 我没有收到错误消息,因为我找不到用于调用 db 上下文的语法,甚至无法尝试将其与可用属性相结合。
  • hmmm.. 这个链接有帮助吗? stackoverflow.com/questions/28599404/…

标签: c# entity-framework-core


【解决方案1】:

csproj 文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>

program.cs:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace EfExperiment
{
    class Program
    {
        public class Record
        {
            public int Id { get; set; }
            public DateTime Date { get; set; }
            public decimal Value { get; set; }
        }

        public class RecordsDbContext : DbContext
        {
            public DbSet<Record> Records { get; set; }

            public List<Record> RecordsByDateRange(DateTime fromDate, DateTime toDate)
            {
                var fromDateParam = new SqlParameter("fromDate", fromDate);
                var toDateParam = new SqlParameter("toDate", toDate);

                return Records
                    .FromSql("EXECUTE dbo.RecordsByDateRange @fromDate, @toDate", fromDateParam, toDateParam)
                    .ToList();
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=RecordsDb;Trusted_Connection=True;");
            }
        }

        static void Main(string[] args)
        {
            using (var dbc = new RecordsDbContext())
            {
                var records = dbc.RecordsByDateRange(DateTime.Now.AddMonths(-1), DateTime.Now);
                Console.WriteLine($"{records.Count} records loaded");

                foreach (var record in records)
                {
                    Console.WriteLine($"[{record.Id}] [{record.Date}] {record.Value}");
                }
            }

            Console.WriteLine("Press <enter>");
            Console.ReadLine();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多