2012-12-19 1 views
0

좋은 오후의 동료 스태커 (또는 당신이 선호하는 어느 쪽이라도), 이것은 무엇보다 청결과 편의 이슈 다. 그러나 내가 그것에 관해 이제까지 이상하게 여기는 단 한사람의 사람인 것을 상상할 수 없다. ..WCF Data Services를 사용하여 DbContext에서 메서드를 직접 참조 할 수 있습니까?

저는 Entity Framework 데이터 컨텍스트를 사용하는 기본 OData 가능 WCF Data Service 클래스를 가지고 있습니다.

[JsonpSupportBehavior] 
public class ControlBindingService : DataService<MyDataContext> 
{ 
    public static void InitializeService(DataServiceConfiguration config) 
    { 
     config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3; 
     config.DataServiceBehavior.AcceptCountRequests = true; 
     config.SetEntitySetAccessRule("*", EntitySetRights.All); 
     config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);   
    } 

    protected override MyDataContext CreateDataSource() 
    { 
     if (HttpContext.Current == null) 
      throw new InvalidOperationException("The WCF Data Services implementation must be hosted in IIS."); 

     string username; 
     if (HttpContext.Current.User.Identity.IsAuthenticated) 
      username = HttpContext.Current.User.Identity.Name; 
     else 
     { 
      // The request didn't have user identity, attempt to find UserName in the 
      // request header before returning 401 to the caller. 
      if (!String.IsNullOrEmpty(HttpContext.Current.Request.Headers["UserName"])) 
      { 
       username = HttpContext.Current.Request.Headers["UserName"]; 
       // REVIEW: We should validate user before passing it to the datacontext. 
      } 
      else 
       throw new DataServiceException(401, "Client did not pass required authentication information."); 
     } 

     return MyDataContext.GetInstance(username); 
    } 

    [WebGet] 
    public List<DailyKeyPerformanceIndicator> GetResourceKPIs(
     int resourceId, string jsonStart, string jsonEnd, int scenarioId) 
    { 
     DateTime start = jsonStart.DeserializeJson<DateTime>(); 
     DateTime end = jsonEnd.DeserializeJson<DateTime>(); 

     if (scenarioId < 1) 
     { 
      scenarioId = CurrentDataSource.GetScenarios() 
       .Single(s => s.IsProduction).ScenarioID; 
     } 

     return CurrentDataSource.GetDailyResourceKPI(
      scenarioId, start, end, resourceId); 
    } 
} 

데이터 컨텍스트 단지 표준 (코드 첫 번째) 특성 등, 엔티티 세트를 노출과 DbContext 구현 ..

을하지만, 우리는 또한 우리가 원하는 일부 테이블을 노출하는가에 대한 방법을 몇 가지 제약 조건을 적용합니다. 특히 (아래 코드 참조) 우리는 호출자가 데이터를 사용하고자하는 것을 알고 싶어하므로 적절한 결과 만 반환 할 수 있습니다. 예를 들어, 호출자가 employees 테이블에서 행을 가져 오려면 모든 행을 가져 오거나 업데이트 권한이있는 행만 가져올 수 있습니다.

[Serializable] 
public partial class MyDataContext : DbContext 
{ 
    static MyDataContext() 
    { 
     Database.SetInitializer<MyDataContext>(null); 
    } 

    public MyDataContext() 
     : base("name=MyDBString") 
    { } 

    // Standard table properties... 

    public DbSet<User> Users 
    { 
     get { return this.Set<User>(); } 
    } 

    public DbSet<UserSetting> UserSettings 
    { 
     get { return this.Set<UserSetting>(); } 
    } 

    public DbSet<SettingDefinition> SettingDefinitions 
    { 
     get { return this.Set<SettingDefinition>(); } 
    }  

// Restricted table methods... 

public DbSet<Client> GetClients(
    DatabasePermissions perms = DatabasePermissions.Select) 
{ 
    // getPermissibleSet is a method in a helper class that does some 
    // magical querying and produces a filtered DbSet. 
    return getPermissibleSet<Client>(perms); 
} 

public DbSet<Employee> GetEmployees(
    DatabasePermissions perms = DatabasePermissions.Select) 
{ 
    // getPermissibleSet is a method in a helper class that does some 
    // magical querying and produces a filtered DbSet. 
    return getPermissibleSet<Employee>(perms); 
}  
} 

지금 문제의 근본에 ... 내가 각각의 모든에 대한 [WebGet]을 쓰고 할 필요가 없도록하고 싶습니다 내 데이터 컨텍스트에 "테이블 방법을 제한". 그 이유는 실제로 이중화 이상의 것입니다. [WebGet] 메서드는 결국 데이터 컨텍스트에 대한 직접 통과가됩니다.

그래서 요약하면 기본적으로해야 할 일은 WCF가 내 DbSet 속성에서와 같은 방식으로 노출하는 데이터 컨텍스트 클래스에서 메서드를 표시하는 것입니다. 어떤 사람?

감사합니다. J

답변

0

이것은 흥미로운 문제입니다. 나는 비슷한 일을하려하고있다. 이것은 일종의 다트 던지기하지만 여기에 뭔가를 시도해 봤어? generics를 분리하여 각 유형마다 고유 한 컨텍스트를 작성하지 않아야하지만 generics로 중복 코드를 제거 할 수 있어야합니다.

[Serializable] 
public partial class MyDataContext<T> : DbContext where T : class 
{ 
    static MyDataContext() 
    { 
     Database.SetInitializer<MyDataContext>(null); 
    } 

    public MyDataContext() 
     : base("name=MyDBString") 
    { } 

    // Standard table properties... 

    public DbSet<T> SettingDefinitions 
    { 
     get { return this.Set<T>(); } 
    } 

    // Restricted table methods... 

    public DbSet<T> GetClients(
     DatabasePermissions perms = DatabasePermissions.Select) 
    { 
     // getPermissibleSet is a method in a helper class that does some 
     // magical querying and produces a filtered DbSet. 
     return getPermissibleSet<T>(perms); 
    } 
} 
관련 문제