programing

엔티티 프레임워크와 함께 저장 프로시저를 호출하는 방법?

codeshow 2023. 9. 19. 21:31
반응형

엔티티 프레임워크와 함께 저장 프로시저를 호출하는 방법?

MySQL 데이터베이스에서 EF4 모델을 생성했으며 저장 프로시저와 테이블을 모두 포함했습니다.

EF에 대해 정기적으로 instert/update/fetch/delete 작업을 수행하는 방법은 알고 있지만 저장 프로시저를 찾을 수 없습니다.

이것이 제가 바라던 바였습니다.

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

편집 1:

EF가 없는 모습은 이렇습니다.

sqlStr = "CALL updateGame(?,?,?,?,?,?,?)";

commandObj = new OdbcCommand(sqlStr, mainConnection);
commandObj.Parameters.Add("@id,", OdbcType.Int).Value = inGame.id;
commandObj.Parameters.Add("@name", OdbcType.VarChar, 255).Value = inGame.name;
commandObj.Parameters.Add("@description", OdbcType.Text).Value = ""; //inGame.description;
commandObj.Parameters.Add("@yearPublished", OdbcType.DateTime).Value = inGame.yearPublished;
commandObj.Parameters.Add("@minPlayers", OdbcType.Int).Value = inGame.minPlayers;
commandObj.Parameters.Add("@maxPlayers", OdbcType.Int).Value = inGame.maxPlayers;
commandObj.Parameters.Add("@playingTime", OdbcType.VarChar, 127).Value = inGame.playingTime;    

return Convert.ToInt32(executeScaler(commandObj));

추신. 필요하다면 EF 버전을 변경할 수 있습니다.

편집 1:

CREATE DEFINER=`106228`@`%` PROCEDURE `updateGame`(
    inId INT,
    inName VARCHAR(255),
    inDescription TEXT,
    inYearPublished DATETIME,
    inMinPlayers INT,
    inMaxPlayers INT,
    inPlayingTime VARCHAR(127)
)

DbContext에서 Database 속성을 사용하는 방법도 있습니다.

SqlParameter param1 = new SqlParameter("@firstName", "Frank");
SqlParameter  param2 = new SqlParameter("@lastName", "Borland");
context.Database.ExecuteSqlCommand("sp_MyStoredProc @firstName, @lastName", 
                              param1, param2);

EF5는 확실히 그것을 지지합니다.

SqlQuery 함수를 사용하고 결과를 매핑할 엔티티를 나타냅니다.

이를 수행하기 위해 예를 보냅니다.

var oficio= new SqlParameter
{
    ParameterName = "pOficio",
    Value = "0001"
};

using (var dc = new PCMContext())
{
    return dc.Database
             .SqlQuery<ProyectoReporte>("exec SP_GET_REPORTE @pOficio",
                                        oficio)
             .ToList();
}

저장 프로시저를 모델에 가져오면 모델 브라우저에서 마우스 오른쪽 단추로 클릭할 수 있습니다.Context.Store/Stored Procedures섹션)을 클릭합니다.Add Function Import. 결과적으로 복잡한 유형이 필요한 경우 바로 거기에서 작성할 수 있습니다.

OP의 원래 요청에 근거해서 이렇게 저장 프로시저를 호출할 수 있다면...

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

무분별한 승객은 이와 같은 엔티티 프레임워크에서 저장 프로시저를 호출할 수 있는 프로젝트를 가지고 있습니다.

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>();
}

... 그리고 저는 저장 프로시저 프레임워크(여기)를 작업하고 있습니다. 아래에 나와 있는 제 테스트 방법 중 하나로 호출할 수 있습니다.

[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)
    {
    }
}

이 두 가지 방법 중 어느 것이라도 좋습니까?

기본적으로 저장 프로시저 매핑을 사용하여 프로시저를 엔티티에 매핑하면 됩니다.

매핑되면 EF에 항목을 추가하는 일반적인 방법을 사용하고 대신 저장 프로시저를 사용합니다.

참고하시기 바랍니다.링크를 참조하십시오.결과적으로 이와 같은 엔티티가 추가됩니다(실제로 저장 프로시저를 사용합니다).

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

이것이 제가 최근에 2008 SQL 데이터베이스를 보유한 데이터 시각화 애플리케이션을 위해 수행한 작업입니다.이 예에서는 저장 프로시저에서 반환된 목록을 받고 있습니다.

public List<CumulativeInstrumentsDataRow> GetCumulativeInstrumentLogs(RunLogFilter filter)
    {
        EFDbContext db = new EFDbContext();
        if (filter.SystemFullName == string.Empty)
        {
            filter.SystemFullName = null;
        }
        if (filter.Reconciled == null)
        {
            filter.Reconciled = 1;
        }
        string sql = GetRunLogFilterSQLString("[dbo].[rm_sp_GetCumulativeInstrumentLogs]", filter);
        return db.Database.SqlQuery<CumulativeInstrumentsDataRow>(sql).ToList();
    }

그리고 내 경우에는 몇가지 포맷에 대한 확장 방법이 있습니다.

public string GetRunLogFilterSQLString(string procedureName, RunLogFilter filter)
        {
            return string.Format("EXEC {0} {1},{2}, {3}, {4}", procedureName, filter.SystemFullName == null ? "null" : "\'" + filter.SystemFullName + "\'", filter.MinimumDate == null ? "null" : "\'" + filter.MinimumDate.Value + "\'", filter.MaximumDate == null ? "null" : "\'" + filter.MaximumDate.Value + "\'", +filter.Reconciled == null ? "null" : "\'" + filter.Reconciled + "\'");

        }

엔티티 프레임워크를 사용하여 MySQL 프로시저를 쿼리하는 예입니다.

MySQL의 저장 프로시저 정의는 다음과 같습니다.

CREATE PROCEDURE GetUpdatedAds (
    IN curChangeTracker BIGINT
    IN PageSize INT
) 
BEGIN
   -- select some recored...
END;

Entity Framework를 사용하여 쿼리하는 방법은 다음과 같습니다.

 var curChangeTracker = new SqlParameter("@curChangeTracker", MySqlDbType.Int64).Value = 0;
 var pageSize = new SqlParameter("@PageSize", (MySqlDbType.Int64)).Value = 100;

 var res = _context.Database.SqlQuery<MyEntityType>($"call GetUpdatedAds({curChangeTracker}, {pageSize})");

C# String 보간법을 사용하여 쿼리 문자열을 작성하고 있습니다.

언급URL : https://stackoverflow.com/questions/14264750/how-to-call-stored-procedures-with-entityframework

반응형