How to call Stored Procedures with EntityFramework?

前端 未结 7 1329
青春惊慌失措
青春惊慌失措 2020-12-01 02:03

I have generated an EF4 Model from a MySQL database and I have included both StoredProcedures and Tables.

I know how to make regular instert/update/fetch/delete oper

7条回答
  •  情话喂你
    2020-12-01 02:33

    Based up the OP's original request to be able to called a stored proc like this...

    using (Entities context = new Entities())
    {
        context.MyStoreadProcedure(Parameters); 
    }
    

    Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

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

    ... 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
    {
        public GetTenantForTenantNameProcedure(
            GetTenantForTenantNameParameters parameters)
            : base(parameters)
        {
        }
    }
    

    If either of those two approaches are any good?

提交回复
热议问题