2013-01-10 2 views
31

MySQL 데이터베이스에서 EF4 모델을 생성했으며 StoredProcedures와 Tables를 모두 포함했습니다.EntityFramework로 저장 프로 시저를 호출하는 방법?

EF에 대해 정기적 인 instert/update/fetch/delete 작업을 수행하는 방법을 알고 있지만 StoredProcedures를 찾을 수 없습니다.

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

PS를

내가 바라던 것이었다. 필요하다면 나는 EF 버전을 변경할 수 있습니다

편집 1 :

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

답변

0

이것은 내가 최근에 2008 SQL 데이터베이스를 가지고 내 데이터 시각화 응용 프로그램에 대한 한 것입니다. 줄리에 의해

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 + "\'"); 

     } 
+0

나는 그것을 얻지 못한다. 왜 SP 이름을 하드 코드해야 하는가? 모델을 생성 할 때 추가했습니다. 컨텍스트 개체의 어딘가에 있지 않아야합니까? – Ivy

-1

읽기 우수 기사 (관련 비디오) : 다음

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

그리고 일부 내 경우 형식이 확장 방법 :이 예에서는 내가 저장 프로 시저에서 반환 된 목록을 잡하고 러먼 (프로그래밍 엔티티 프레임 워크의 저자)

Stored Procedures in the Entity Framework

+1

간단한 StoredProcedure를 실행하기위한 텍스트가 많이 없습니다. EF가 SP를 더 많이 잊어 버린 것처럼 느껴 집니까? 왜 문맥 객체가 메소드가 아닌지? Thay가 모델 생성 중에 추가 되었습니까? – Ivy

+0

이것은 의도적으로 설계된 것입니다. 컨텍스트 오브젝트는 단순히'ObjectSet '입니다. 그리고 예, SP로 놀기는'IQueryable '과 같이하지 않습니다 – Tilak

+0

그리고 이것이 우리가 링크 전용 게시물을 막는 이유입니다. 이제 링크가 Entity Framework 홈페이지로 이동합니다. – saluce

57

한 가지 방법은 DbContext 떨어져 데이터베이스 속성을 사용하는 것입니다 :

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

EF5가이를 분명히 지원합니다.

+0

나는 그것을 얻지 못한다. 왜 나는 SP 이름을 하드 코드해야만 하는가? 모델을 생성 할 때 추가했습니다. 컨텍스트 개체의 어딘가에 있지 않아야합니까? – Ivy

+1

예, 모델에 링크하지 않고 _raw_ 액세스를 원한다면 수행하는 방법입니다. –

+1

이것은 저장된 프로 시저를 비 쿼리로 실행하기 만합니다. 반환 된 테이블을 읽을 수 없습니다. –

4

모델에 저장 프로 시저를 가져 오면 모델 브라우저에서 Context.Store/Stored Procedures 섹션의 마우스 오른쪽 버튼을 클릭하고 Add Function Import을 클릭합니다. 결과적으로 복잡한 유형이 필요한 경우 바로 만들 수 있습니다.

+0

시도했지만 매개 변수가있는 메서드를 생성하지 않습니다? 매개 변수를 퍼팅하는 방법을 모르십니까? – Ivy

+1

프로 시저에 매개 변수가 있으면 추가됩니다. – user1908061

+0

아니요? – Ivy

8

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

쿼리에 의해 반환 된 결과 테이블을 나타내는'ProyectoReporte' 클래스를 선언해야합니다 –

0

은 기본적으로 당신은 저장 프로 시저 매핑을 사용하여 엔티티 절차를 매핑해야합니다 :이 작업을 수행하기로

나는 예를 보냅니다.

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

참조 : This Link 둘러보기. 결과는 OP의 원래 요청과 같은 저장된 프로 시저를 호출 할 수 있기를 바탕으로 (실제로 저장 프로 시저를 사용합니다)과 같이 엔티티를

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

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

추가 할 예정입니다 ...

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

Mindless passenger

는이 같은 엔티티 프레임 워크에서 저장된 프로 시저를 호출 할 수있는 프로젝트 ....

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

을 가지고 ... 그리고 나는 stored procedure framework (here) 일하고있는 그 두 가지 방법 중 하나가 좋은 경우에 당신은 ... 아래 내 테스트 방법 중 하나처럼

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

를 호출 할 수 있습니다?

관련 문제