如何使用实体框架工作调用Sql用户定义函数使用LInq c#代码第一种方法

时间:2016-11-03 10:54:20

标签: c# entity-framework linq

我正在使用Entity frame work 6.0.0.0。我有一个返回3列的sql函数 2 guid和一个varchar(userid,ticketid,number)。 但是如何使用ADO.net组件调用此自定义sql函数。 AS Iam使用实体框架工作(代码优先方法)。

1 个答案:

答案 0 :(得分:0)

我有同样的东西:一个派生自DbContext的类,有几个DbSet属性和一个存储过程。我添加了三个功能:

  • 检查存储过程是否存在
  • 创建或更改存储过程(迁移时需要)
  • 调用存储过程。

你的问题是关于最后一部分。你可能也想要其他的,所以这里有三个函数

public class InvoiceContext : DbContext
{
    // DbSet properties left out

    #region stored procedures
    private const string StoredProcedureNameProcessUsageCosts = "processusagecosts";

    public void CallStoredProcedureProcessUsageCosts(UsageCosts usageCosts)
    {
        object[] functionParameters = new object[]
        {
            new SqlParameter(@"ReportDate", usageCosts.ReportPeriod),
            new SqlParameter(@"CustomerContractId", usageCosts.CustomerContractId),
            new SqlParameter(@"CallType", usageCosts.CallType),
            new SqlParameter(@"TariffGroup", usageCosts.TariffGroup),
            new SqlParameter(@"VatValue", usageCosts.VatValue),
            new SqlParameter(@"PurchaseCosts", usageCosts.PurchaseCosts),
            new SqlParameter(@"RetailCosts", usageCosts.RetailCosts),
        };

        const string sqlCommand = @"Exec " + StoredProcedureNameProcessUsageCosts
            + " @ReportDate, @CustomerContractId, @CallType, @TariffGroup, @VatValue,"
            + " @PurchaseCosts, @RetailCosts";
        this.Database.ExecuteSqlCommand(sqlCommand, functionParameters);
    }

    public bool StoredProcedureProcessUsageCostsExists()
    {
        return this.Exists(StoredProcedureNameProcessUsageCosts);
    }

    public void CreateProcedureProcessUsageCosts(bool forceRecreate)
    {
        bool storedProcedureExists = this.Exists (StoredProcedureNameUpdateUsageCosts);

        // only create (or update) if not exists or if forceRecreate:
        if (!storedProcedureExists || forceRecreate)
        {   // create or alter:
            var x = new StringBuilder();

            // ALTER or CREATE?
            if (!storedProcedureExists)
            {
                x.Append(@"CREATE");
            }
            else
            {
                x.Append(@"ALTER");
            }

            // procedure name:
            x.Append(@" procedure ");
            x.AppendLine(StoredProcedureNameProcessUsageCosts);

            // parameters:
            x.AppendLine(@"@ReportPeriod int,");
            x.AppendLine(@"@CustomerContractId bigint,");
            x.AppendLine(@"@CallType nvarChar(80),");
            x.AppendLine(@"@TariffGroup nvarChar(80),");
            x.AppendLine(@"@VatValue decimal(18, 2),");
            x.AppendLine(@"@PurchaseCosts decimal(18, 2),");
            x.AppendLine(@"@RetailCosts decimal(18, 2)");

            // code
            x.AppendLine(@"as");
            x.AppendLine(@"begin");
            x.AppendLine(@"Merge [usagecosts]");
            x.AppendLine(@"Using (Select @ReportPeriod as reportperiod,");
            x.AppendLine(@"              @CustomerContractId as customercontractId,");
            x.AppendLine(@"              @CallType as calltype,");
            x.AppendLine(@"              @TariffGroup as tariffgroup,");
            x.AppendLine(@"              @VatValue as vatvalue)");
            x.AppendLine(@"              As tmp ");
            x.AppendLine(@"On ([usagecosts].[reportperiod] = tmp.reportperiod");
            x.AppendLine(@"AND [usagecosts].[customercontractId] = tmp.customercontractid");
            x.AppendLine(@"AND [usagecosts].[calltype] = tmp.calltype");
            x.AppendLine(@"AND [usagecosts].[tariffgroup] = tmp.tariffgroup");
            x.AppendLine(@"AND [usagecosts].[vatvalue] = tmp.Vatvalue)");
            x.AppendLine(@"When Matched Then ");
            x.AppendLine(@"    Update Set [usagecosts].[purchasecosts] = [usagecosts].[purchasecosts] + @purchasecosts,");
            x.AppendLine(@"               [usagecosts].[retailcosts] = [usagecosts].[retailcosts] + @retailcosts");
            x.AppendLine(@"When Not Matched Then");
            x.AppendLine(@"    Insert (ReportPeriod, CustomerContractId, calltype, tariffgroup, vatvalue, purchasecosts, retailcosts)");
            x.AppendLine(@"    Values (@reportPeriod, @CustomerContractId, @CallType, @TariffGroup, @VatValue, @PurchaseCosts, @RetailCosts);");
            x.AppendLine(@"end");
            this.Database.ExecuteSqlCommand(x.ToString());
        }
        // else: procedure exists and no forced recreate, nothing to do
    }
    #endregion stored procedures
}

用法:

调用存储过程

using (var dbContext - new InvoiceContext(...))
{
    UsageCosts params = new UsageCosts()
    {
        ...
    };
    dbContext.CallStoredProcedureUsageCost(params);
}

创建存储过程

在初始播种数据库期间或在您的某个迁移功能中,在InitializeDataBase中执行此操作

public override void InitializeDatabase(InvoiceContext context)
{
     // if not exists, create the stored procedure
     context.CreateProcedureProcessUsageCosts(false);
}