How to get output result from stored procedure use Entity Framework in C#?

前端 未结 2 1251
太阳男子
太阳男子 2021-01-18 21:25

I\'m working on an ASP.NET MVC project; my goal is to prepare a report from a table so, the first time I\'ve wrote Linq code but it was too slow.

And after that I\'

2条回答
  •  再見小時候
    2021-01-18 22:21

    You can declare your stored procedures using

    CREATE PROCEDURE [dbo].YourStoredProcedure
        @Start DATETIME, 
        @END   DATETIME
    AS
    

    Then you can get rid of the code needed to cast from string

    In order to get the results mapped as a c# object, you need to use SqlQuery or FromSql depending on the version of Entity Framework that you are using

    Entity Framework 6

    var result = dbContext.Bar.SqlQuery("EXEC YourStoredProcedure").ToList();
    

    To pass a parameter, you woild do something like

    var result = dbContext.Bar.SqlQuery("EXEC YourStoredProcedure @SomeParameter", 
                 new SqlParameter("@SomeParameter", TheParameterValue)).ToList();
    

    And for Entity Framework Core 2

    var result = dbContext.Bar
    .FromSql("EXEC YourStoredProcedure")
    .ToList();
    

    Where Bar is your C# object declared as a property with type DbSet in your dbContext class

    Based on your output you should create a C# object similar to

    public class Bar
    {
         public datetime DateRecSlash { get; set; }
         public int CodeMarz { get; set; }
    }
    

提交回复
热议问题