2014-11-13 2 views
0

엔터티 프레임 워크 데이터베이스를 처음 사용할 때 생성자를 보호하려면 어떻게합니까? 내 데이터베이스에서 엔터티 데이터 모델을 생성 할 때 자동 생성 된 클래스는 public 생성자를 포함엔터티 프레임 워크 데이터베이스의 첫 번째 보호 된 생성자

,

//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated from a template. 
// 
//  Manual changes to this file may cause unexpected behavior in your application. 
//  Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace Domain.Models 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class MyClass 
    { 
     public MyClass() 
     { 

은 제가하고 싶은 것은 당신은 캔트이 보호 된 생성자

public partial class MyClass 
    { 
     protected MyClass() 
     { 
+0

초기 반응은 모델을 새로 고침하면 수동으로 변경 사항을 덮어 쓸 수 있기 때문에 데이터베이스에서 처음에는 불가능하다고 생각합니다. – IronMan84

+0

왜 그렇게하고 싶습니까? 이 방법으로이 클래스의 인스턴스를 만드는 것은 불가능합니다. 사용자가 기본 클래스를 인스턴스화하지 못하게하려고합니까? 그런 다음 디자이너에서 기본 클래스를 추상으로 표시 할 수 있는지 확인하십시오. –

+0

@PanagiotisKanavos 내 모델 상태가 유효 함을 보장 할 수 있도록 특정 서명이 필요한 부분 클래스를 만듭니다. 예 : MyClass (person person) {this.Person = person }. 자세한 설명을 보려면 여기를 참고하십시오. http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/ –

답변

3

당신은 모델 클래스를 생성하는 T4 템플릿을 수정하여이 작업을 수행 할 수 있습니다.

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection)) 
{ 
    fileManager.StartNewFile(entity.Name + ".cs"); 
    BeginNamespace(code); 
#> 
<#=codeStringGenerator.UsingDirectives(inHeader: false)#> 
<#=codeStringGenerator.EntityClassOpening(entity)#> 
{ 
<# 
    var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); 
    var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); 
    var complexProperties = typeMapper.GetComplexProperties(entity); 

    if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) 
    { 
#> 
    public <#=code.Escape(entity)#>() 
    { 
<# 

및 개체 유형에 대한 보호 생성자를 만듭니다

protected <#=code.Escape(entity)#>() 

이 변경에 의해 결론 public <#=code.Escape(entity)#>()을 대체 : 파일의 상단에이 부분을 찾아보십시오. 파일의 아래쪽에 복잡한 유형에 대한 유사한 구문이 있으므로 해당 형식도 수정할 수 있습니다.

"업데이트"에 대한 단어. 데이터베이스에서 모델을 업데이트하면 이러한 변경 사항을 덮어 쓰지 않습니다. 그러나 업데이트 EF 인 경우 수정 된 t4 템플릿의 문제는 새 버전의 템플릿을 사용하려고 할 때 다시해야한다는 것입니다.

1

입니다 보호 된 Model 생성자가 잘못되었습니다. 상황에 따라 다를 수 있음 - Gert에서 제공 한 링크 참조. http://msdn.microsoft.com/en-us/library/vstudio/dd468057%28v=vs.100%29.aspx 수정을 위해 Gert에게 감사드립니다.

T4를 통해 변경할 수 있습니다.

문제를 해결하는 가장 좋은 방법은 아직도 있습니까?

데이터가 올바른지 확인하기 위해 EF에서 저장 작업 중에 호출 할 유효성 검사 인터페이스 IValidatableObject 과 같은 것을 사용할 수 있습니다.

데이터를 읽을 때 EF는 poco 인스턴스를 채우고 컨텍스트에서 참조를 고정합니다. POCO 인스턴스를 채울 때 원하는 경우 유효성 검사를 트리거 할 수 있습니다. ef는 저장하기 전에 validate를 호출합니다. 이 주제에 대한 Google 검색.

예를 들어

/// <summary> 
    /// Get called everytime a Validation is triggered on an object. EG MVC model check or EF save. 
    /// </summary> 
    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { 

     // Sample Implementation. 
     var validationResult = new List<ValidationResult>(); 

     // a field cant be null or empty when condition X is true. 
     if (SOME CONDTION that is true ) { 
      validationResult.Add(new ValidationResult(some field is required when...", new List<string>() {"FieldName"})); 
      } 

     return validationResult; 
    } 
+1

Phil, EF는 보호 된 생성자 (및 심지어 개인 멤버)도 처리 할 수 ​​있습니다. 특정 시나리오 (예 : http://msdn.microsoft.com/en-us/library/vstudio/dd468057%28v=vs.100%29)에도 권장됩니다. aspx. –

+0

분명히이 문서 정리가 더 좋은 정보입니다. Gert에게 감사드립니다. –

+0

@philsoady 이미 유효성 검사를 사용하고 있습니다.이 문제는 유효성 확인 및 모델 상태 중 하나가 아니며, 비즈니스 도메인은 매우 복잡한 개념이므로 모호성을 방지하기 위해 API를 노골적인 의도로 만듭니다. 예를 들어 평가 **는 항상 Instituion에 대해 수행되므로 새로운 평가()는 비즈니스 규칙을 위반합니다. '새로운 평가 (기관)'이 유효합니다. 자세한 설명은 http://lostechies.com/jimmybogard/2010/02/24/strengthening-your-domain-aggregate-construction/을 참조하십시오. –

관련 문제