如何在实体框架中使用“存储过程”中的“选择”结果

时间:2014-03-29 07:52:13

标签: c# entity-framework stored-procedures

我的存储过程如下所示:

ALTER PROCEDURE [dbo].[Save_Customer](@PK int , @Name nvarchar(30) , @Address nvarchar(100) , @CustomerGrp_FK int)
AS 
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN
BEGIN TRY
    IF (@PK = -1)   
    BEGIN
        INSERT INTO dbo.[Customer]
        SELECT @Name  , @Address  , @CustomerGrp_FK 

        SELECT SCOPE_IDENTITY () as IdentityPK
    END
    ELSE
    BEGIN
        UPDATE Customer
        SET Name  = @Name ,Address  = @Address ,CustomerGrp_FK  = @CustomerGrp_FK
        WHERE PK= @PK
    END

要使用SELECT SCOPE_IDENTITY () as IdentityPK,我创建了以下类:

public class Save_Customer_MyResult
{
    public int Identity { get; set; }
}

然后我在我的EntityContext类中插入以下代码:

public DbSet<Save_Customer_MyResult> Save_CustomerDB { get; set; }

public virtual  Save_Customer_MyResult Save_Customer1(Nullable<int> pK, string name, string address, Nullable<int> customerGrp_FK)
    {
        return this.Database.SqlQuery<Save_Customer_MyResult>("Save_Customer @PK, @Name, @Address, @CustomerGrp_FK", new System.Data.SqlClient.SqlParameter("PK", pK)
            , new System.Data.SqlClient.SqlParameter("Name", name)
            , new System.Data.SqlClient.SqlParameter("Address", address)
            , new System.Data.SqlClient.SqlParameter("CustomerGrp_FK", customerGrp_FK)).First<Save_Customer_MyResult>();
    }

现在在我的演示文稿中。当我打电话给方法。 Identity字段为0 :(

Customer.Save_Customer_MyResult scr=customercontext.Save_Customer1(-1, txt_Name.Text, txt_Address.Text, Int32.Parse(cmb_GroupName.SelectedValue.ToString()));

       MessageBox.Show(scr.Identity  .ToString());

1 个答案:

答案 0 :(得分:1)

1-根据this article。我刚刚制作了一个新的Complex Type

stored procedure mapping

的{entity

enter image description here

3 - 然后:

IEnumerable<Customer.Save_Customer_Result > s= customercontext.Save_Customer(-1, txt_Name.Text, txt_Address.Text,Int32 .Parse( cmb_GroupName.SelectedValue.ToString()));
       MessageBox.Show(s.First<Customer.Save_Customer_Result>().IdentityPK   .ToString());