3

EF4, CTP5와 함께 코드 우선 POCO를 사용하고 있습니다. 나는 그것에 열이 많은 테이블을 가지고있다 (100 이상). 필자는 테이블을 여러 유형 (일명 "테이블 분할")으로 분할하여 일부 기본 정보가 필요할 때마다 모든 데이터를 가져올 필요가 없도록하고 싶습니다.먼저 EF4 코드에서 여러 유형으로 표를 분할하려면 어떻게합니까?

Google에서이 문서를 찾을 수없는 것 같습니다. 개념에 대한 참조 인 "Table Splitting"을 발견했으며, EDMX 파일을 사용하여 코드를 수행하는 방법을 보았지만 코드 우선의 샘플은 찾지 못했습니다.

나는 그것을 ...

다른 엔티티 유형을 정의하고 그렇게 같은 다른 탐색 속성 ...

public class User 
{ 
    public int UserID { get; set; } 
    public string UserName { get; set; } 
    [ForeignKey("UserID")] 
    public virtual UserDetails Details { get; set; } 
} 

public class UserDetails 
{ 
    public int UserID { get; set; } 
    public string MoreData { get; set; } 
    [ForeignKey("UserID")] 
    public virtual User User { get; set; } // nice to have, but not required 
} 

과 내가 같이 호출하는 것처럼 그들을 관련된 것처럼 간단 할 것이라고 기대했다

return (from u in Context.Users // <-- error occurs here 
     where u.UserID == userID 
     select u).FirstOrDefault(); 

불행히도 이것은 작동하지 않는 것 같습니다. 나는이 작업을 수행 할 때 속성이 오류가 멀리 이동하게 User.Details 제거 ...

[IndexOutOfRangeException: Index was outside the bounds of the array.] 
    System.Data.Entity.ModelConfiguration.Conventions.Edm.PropertyMaxLengthConvention.System.Data.Entity.ModelConfiguration.Conventions.Edm.IEdmConvention<System.Data.Edm.EdmAssociationType>.Apply(EdmAssociationType associationType, EdmModel model) +598 
    System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.Dispatch(TEdmDataModelItem item) +100 
    System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmAssociationType(EdmAssociationType item) +22 
    System.Data.Entity.ModelConfiguration.Edm.Services.DataModelItemVisitor.VisitCollection(IEnumerable`1 collection, Action`1 visitMethod) +267 
    System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitAssociationTypes(EdmNamespace edmNamespace, IEnumerable`1 associationTypes) +75 
    System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitEdmNamespace(EdmNamespace item) +91 
    System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmNamespace(EdmNamespace item) +32 
    System.Data.Entity.ModelConfiguration.Edm.Services.DataModelItemVisitor.VisitCollection(IEnumerable`1 collection, Action`1 visitMethod) +267 
    System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitNamespaces(EdmModel model, IEnumerable`1 namespaces) +75 
    System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitEdmModel(EdmModel item) +47 
    System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmModel(EdmModel item) +45 
    System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModel(EdmModel model) +254 
    System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel) +257 
    System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection) +172 
    System.Data.Entity.Internal.LazyInternalContext.CreateModel() +62 
    System.Lazy`1.CreateValue() +361 
    System.Lazy`1.LazyInitValue() +104 
    System.Lazy`1.get_Value() +89 
    System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +358 
    System.Data.Entity.Internal.InternalContext.Initialize() +16 
    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16 
    System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +61 
    System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider() +15 
    System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +13 
    System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63 
    TourFactory.Web.AgentWebsite.Models.Websites.WebsiteRepository.GetUser(Int32 userID) in C:\Code\hdtf\TF4\Web\AgentWebsite\Models\Websites\WebsiteRepository.cs:28 
    TourFactory.Web.AgentWebsite.Controllers.WebsiteController.get_Agent() in C:\Code\hdtf\TF4\Web\AgentWebsite\Controllers\WebsiteController.cs:42 
    TourFactory.Web.AgentWebsite.Controllers.WebsiteController.OnActionExecuting(ActionExecutingContext filterContext) in C:\Code\hdtf\TF4\Web\AgentWebsite\Controllers\WebsiteController.cs:55 
    System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) +39 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +81 
    System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +61 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 
    System.Web.Mvc.Controller.ExecuteCore() +136 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232 
    System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 
    System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 
    System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42 
    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 
    System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +61 
    System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31 
    System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 

을 다음과 같은 오류를 얻고있다, 그러나 나는 EF4의 멋진 탐색 기능을 사용할 수 없습니다.

답변

4

사용 복잡한 유형은 테이블을 여러 유형으로 매핑 할 수있는 유일한 방법입니다. 그러나 코드 우선 (일반적으로 EF)은 복잡한 유형의 지연/지연로드를 지원하지 않습니다. 정말 다음 여러 테이블로 분할하여 당신이 당신의 큰 테이블에 대한 게으른 로딩을 달성 할 수

public class User 
{ 
    public int UserID { get; set; } 
    public string UserName { get; set; } 
    public UserDetails Details { get; set; } 
} 

[ComplexType] 
public class UserDetails 
{ 
    public string MoreData { get; set; } 
} 

유일한 방법 : 즉, EF는 항상 복합 형에게 당신이 데이터베이스에서 개체를 읽을 때마다 웁니다 일대일 연결을 사용하여 여러 엔티티로 다시 매핑 할 수 있습니다.
Associations in EF Code First CTP5: Part 1 – Complex Types

+0

덕분에 (분할 "사람"테이블 줄리아 러먼의 책에서와 같은 유창함의 API에서 1 초 등을. 나는 더 나은 솔루션을 기대했다. 나는 우리의 레거시 데이터베이스를 지원하기 위해 NHibernate로 전환 할 필요가 있는지 궁금해하고있다. – Brian

+0

미안하다. 나는 당신에게 더 나은 대답을 주었으면 좋겠다 .Hibernate가 Complex Types에서이 기능을 지원한다고 생각한다. 그것은 같은 개념입니다.) 불행히도 이것은 EF 팀에게는 우선 순위가 낮은 항목이므로 올해 말에 RTM에서이 기능을 사용할 가능성은 거의 없습니다. –

+0

@Brian : 검색어에 투영법을 사용하면 문제가 없습니다. 또는 코드 첫 번째를 포기하고 QueryView 기능을 사용하십시오. –

0

내가 아는이 질문은 년 만 EF 코드 먼저 테이블 분할 및 지연로드를 지원합니다 이상입니다 :

는 EF 코드 첫 CTP에서 복잡한 유형에 대한 자세한 정보를 원하시면,이 기사를 살펴 동시에.

귀하의 모델은 다음과 같이해야한다 : 예상대로

[Table("UserTable")] 
public class User 
{ 
    [Key, ForeignKey("Details")] 
    public int UserID { get; set; } 
    public string UserName { get; set; } 
    public virtual UserDetails Details { get; set; } 
} 

[Table("UserTable")] 
public class UserDetails 
{ 

    [Key, ForeignKey("User")] 
    public int UserID { get; set; } 
    public string MoreData { get; set; } 
    public virtual User User { get; set; } 
} 

게으른 로딩 (열망 로딩) 작동합니다.

  • 엔티티는 1 대 1 관계가있는 경우 해당 테이블의 분할이 작동합니다, 그리고
  • 엔티티의 향기가 제시 한 동일한 키
0

것 같아요 답을 공유하는 것이 중요합니다 더 나은 사람입니다. 결국 당신은 똑같은 것을 성취합니다. 그러나 두 번째 경우의 경우 똑같은 일을해야합니다. 타사 코드로 인해 [ComplexType]을 적용 할 수 없거나 해당 유형의 목록이있는 경우 처음에는 문제가 발생할 수 있습니다.

사용 "사람"과 "PersonPhoto"엔티티.

modelBuilder.Entity<Person>().ToTable("People"); 
    modelBuilder.Entity<PersonPhoto>().ToTable("People"); 
관련 문제