简体   繁体   English

在实体框架中使用存储过程

[英]Use a stored procedure in entity framework

I have a model-first EF model. 我有一个模型优先的EF模型。 I just imported the first stored procedure: cpas_POIDVendorProjectDate 我刚刚导入了第一个存储过程: cpas_POIDVendorProjectDate

I imported it as a function. 我将其导入为函数。 It has three input parameters: @ProjectID(int) , @VendorID(int) , and @Workdate(datetime) , and returns @POID(int) . 它具有三个输入参数: @ProjectID(int)@VendorID(int)@Workdate(datetime) ,并返回@POID(int)

Here's the SQL code: 这是SQL代码:

 CREATE PROCEDURE [dbo].[cpas_POIDVendorProjectDate]
    @VendorID int,
    @ProjectID int,
    @WorkDate datetime,
    @PO_ID int OUTPUT
 AS
 BEGIN
    SET NOCOUNT ON;

    DECLARE @RowCount int;

       SELECT @PO_ID = ID FROM tblPO WHERE 
        VendorID = @VendorID
        AND ExpirationDate >= @WorkDate
        AND (ProjectID IS NULL OR ProjectID = @ProjectID)
        AND CapitalExpense = (
          SELECT CapitalExpense FROM tblProjects WHERE ID=@ProjectID)
        AND GroupCode in (1,3,5);

     SET @RowCount = @@RowCount;

     IF (@RowCount != 1)
       SET @PO_ID = -1*@RowCount;

END

I called it in my c# program as follows: 我在c#程序中按如下方式调用它:

context.cpas_POIDVendorProjectDate(
    currVendorID, currProjectID, currWorkDate, currPOID);

Intellisense says my use of "context" is wrong...It's a "variable", and I'm using it as a "method". Intellisense说我对“上下文”的使用是错误的……这是一个“变量”,我将其用作“方法”。

In addition, currPOID is rejected because it's looking for a system.data.objects.OjbectParameter , not an int . 另外, currPOID被拒绝,因为它正在寻找system.data.objects.OjbectParameter ,而不是int Intellisense is happy with the function name and other parameters (strangely...) Intellisense对函数名称和其他参数感到满意(奇怪的是...)

What am I doing wrong here? 我在这里做错了什么?

You can always do this if nothing else works: 如果没有其他效果,您可以始终这样做:

using(var context = new MyDataContext())
{
    using(var cmd = context.Database.Connection.CreateCommand())
    {
        cmd.CommandText = "cpas_POIDVendorProjectDate";
        cmd.CommandType = CommandType.StoredProcedure;
        //if the stored proc accepts params, here is where you pass them in
        cmd.Parameters.Add(new SqlParameter("VendorId", 10));
        cmd.Parameters.Add(new SqlParameter("ProjectId", 12));
        cmd.Parameters.Add(new SqlParameter("WorkDate", DateTimw.Now));
        var poid = (int)cmd.ExecuteScalar();
    }
}

If you would like an object orientated way, then Mindless passenger has a project that allows you to call a stored proc from entity frame work like this.... 如果您想要一种面向对象的方式,那么Mindless passenger有一个项目可以让您从这样的实体框架中调用存储的proc。

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework ( here ) which you can call like in one of my test methods shown below... ...并且我正在开发一个存储过程框架在这里 ),您可以像下面显示的一种测试方法中那样调用它...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good? 这两种方法中的任何一种是否有用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM