데이터베이스에 저장하기 전에 도메인 엔터티 속성을 고유하게 확인해야하는 시나리오가 있습니다. 다음은 간단한 제품 클래스입니다. 내가 도메인 기반 설계를 사용하고 있기 때문에도메인 엔터티의 고유 값 유효성 검사
public class Product : EntityBase
{
int ID { get; set; }
string ProductKey { get; set; }
int CategoryID { get; set; }
bool IsValid
{
get
{
if (string.IsNullOrEmpty(ProductKey))
{
ValidationErrors.Add("ProductKey Required.");
}
if (CategoryID == 0)
{
ValidationErrors.Add("CategoryID Required.");
}
/* Validation that the product key is unique could go here? i.e. requires a database read. */
return ValidationErrors.Count() == 0;
}
}
}
제품 엔티티가 지속성 또는 서비스 계층에 대한 지식이 없습니다 :의 내가 의 Productkey 문자열 속성이 고유하는 새로운 제품을 만들 때 유효성을 검사 할 가정하자.
public class ProductService
{
private IProductRepository _productRepository = new ProductRepository();
public int CreateProduct(Product item)
{
if (item.IsValid)
{
if (ProductKeyIsUnique(item.ProductKey))
{
_productRepository.Add(item);
}
else
{
throw new DuplicateProductKeyException();
}
}
}
private bool ProductKeyIsUnique(string productKey)
{
return _productRepository.GetByKey(productKey) == null;
}
}
이 충분히 간단하지만 이상적으로 나는 도메인 모델에 사는 같은 논리를하고자 다음과 같이 그냥 서비스 방법에 수표를 추가 할 수 있습니다. 아마도 서비스 계층에서 발견 할 수있는 일종의 유효성 검사 이벤트를 제기하는 것일까?
이러한 유형의 시나리오에 대한 모범 사례 또는 알려진 디자인 패턴이 있습니까?
중요하거나 다른 속성에 의존하는 속성에 대한 공개 설정자가 없어야합니다. 그렇게하면 엔터티는 언제든지 일관성없는 상태로 설정할 수 있습니다. 여기를 읽으십시오 : http://blog.gauffin.org/2012/06/protect-your-data/ – jgauffin
물론,하지만 이것은 제 질문을 전달하는 간단한 예일뿐입니다. 이 경우에 재산 세터를 개인적으로 도와 주면 어떻게됩니까? 내 도메인 모델에 데이터 액세스 문제를 추가합니까? –
DDD에서 그렇게하지 않는다고 가정 할 수는 없습니다. 내가 볼 수있는 것은 도메인 엔티티의 캡슐화를 중단하는 예제입니다. 하지만 질문에 대답하지 않았기 때문에 그냥 코멘트를 남겨 두었습니다. – jgauffin