簡體   English   中英

使用實體框架執行存儲過程

[英]Execute stored procedure using entity framework

是否可以使用EF執行存儲過程,使用內連接和左外連接從兩個或多個表中選擇數據庫中的記錄。

我的觀點是避免在EF或LINQ中進行連接的方法,我有很多問題。

因此,如果我創建該過程,我可以使用來自用戶輸入的參數調用它,可以將結果分配給.ToList()方法,然后將結果添加到asp:repeater .DataSource

我知道這可能是一個奇怪的問題,但我想首先要做這個,使用EF因為我感覺更舒服。 第二,擺脫在EF中使用連接。 第三,我在某處讀到,當用於經常調用查詢時,使用存儲過程將提高查詢性能。

如果有人可以幫助我用一個例子回答這些問題,我將不勝感激。

您可以從Entity Framework數據上下文中調用SqlQuery

context.Database.SqlQuery<YourType>("exec usp_StoredProcedure").ToList()

作為示例,您需要一個類來映射查詢結果:

public class YourType
{
   public string Property1 { get; set; }
   public string Property2 { get; set; }
}

您還可以為查詢指定參數,如下所示:

SqlParameter parameter1 = new SqlParameter("@Parameter1", "Value");
context.Database.SqlQuery<YourType>("exec usp_StoredProcedure @Parameter1", parameter1).ToList()

我們將看到如何在Entity Framework中執行存儲過程,在MVC中我們將看到如何添加EF。

在數據庫中執行以下腳本以創建存儲過程。

CREATE PROCEDURE FETCHEMPLOYEES AS
BEGIN
    SELECT * FROM EMPTABLE
END

CREATE PROCEDURE FETCHEMPLOYEE(@ID INT) AS
BEGIN
  SELECT * FROM EMPTABLE WHERE ID = @ID
END



public class EmpModel
{
    EmployeeEntities empdb = new EmployeeEntities();

    public List<EMPTABLE> GetEmployees()
    {
       return empdb.FETCHEMPLOYEES().ToList();  
    }

    public EMPTABLE GetEmployee(int? id)
    {
        return empdb.FETCHEMPLOYEE(id).ToList().Single();
    }
}

public class EmployeeController : Controller
{
    Models.EmpModel mod = new Models.EmpModel();

    public ActionResult Index()
    {
        List<EMPTABLE> result = mod.GetEmployees();
        return View(result);
    }

    public ActionResult Details(int id)
    {
        EMPTABLE result = mod.GetEmployee(id);
        return View(result);
    }
}

有關更多分步詳細信息,請參閱以下鏈接: http//dotnetvisio.blogspot.in/2014/01/execute-stored-procedure-using-entity.html

你可以使用ObjectContext類的ExecuteFunction

 public virtual ObjectResult<CustomClassForStoreReturnedData> NameOfStoredProcedure(Nullable<int> tableID)
    {
        var IDParameter = tableID.HasValue ?
            new ObjectParameter("tableID", tableID) :
            new ObjectParameter("tableID", typeof(int));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<CustomClassForStoreReturnedData>("NameOfStoredProcedureInSQLDatabase", IDParameter);
    }

在您使用實體框架與MySQL:

在這個例子中,我的存儲過程期望一個名為myParam的參數,類型為BIGINT

var myParam = new SqlParameter("@myParam", (MySqlDbType.Int64)).Value = 100;

var res = _context.Database.SqlQuery<MyEntity>($"call MyProcedureName({pyParam})");

請注意,我使用C#String Interpolation來構建我的查詢字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM