如何管理IAggregateRoot的Guard.Against.NotFound



我想知道我们是否要检查是否添加新项目,如果projectId存在于db中,shell我们以某种方式在AddItem方法中插入Guard.Agains.NotFound(???)或不?我问是因为如果创建一些实体:

public class Country : BaseEntity<int>, IAggregateRoot
{
public string Name { get; private set; }
private readonly List<District> _districts = new List<District>();
public IEnumerable<District> Districts => _districts.AsReadOnly();
public Country(string name)
{
Name = Guard.Against.NullOrEmpty(name, nameof(name));
}
public void AddDistrict(District newDistrict)
{
Guard.Against.Null(newDistrict, nameof(newDistrict));
Guard.Against.NegativeOrZero(newDistrict.CountryId, nameof(newDistrict.CountryId));
_districts.Add(newDistrict);
}
}

public class District : BaseEntity<int>, IAggregateRoot
{
public string Name { get; set; }
public int CountryId { get; set; }
public List<Municipality> Municipalities { get; set; }
}

如何验证请求发送的countryId是否存在于DB中?例如,如果创建集成测试如下:

[Fact]
public async Task AddDistrict()
{
var districtName = "District";
var countryRepository = GetCountryRepository();
var country = new Country("Country");
await countryRepository.AddAsync(country);
var district = new District
{
CountryId = 2,
Name = districtName
};
country.AddDistrict(district);
await countryRepository.UpdateAsync(country);
Assert.Equal(1, district.Id);
}

无论我把强度值作为CountryId测试将通过,直到不是0或负整数,但我想检查国家实体的id是否存在于DB中。管理这张支票的最佳地点是哪里?认为,

最简单的方法是请求将Country对象提供给District的构造函数:

public class District
{
public string Name { get; private set; }
public int CountryId { get; private set; }
public District(string name, Country country)
{
if (country == null)
throw new Exception("Missing country.");
Name = name;
CountryId = country.Id
}
}

现在您已经强制该域的客户端提供一个国家。如果客户机(应用层)不能从国家存储库中检索一个有效的国家基于提供的id那么你constructur要扔在零的国家。


或者,将CountryId作为District的构造函数参数,使District构造函数成为内部的,这样它就不能在域之外创建,然后使Country对象成为District的工厂:

public class Country
{
public District CreateDistrict(string name)
{
return new District(name, this.Id);
}
}

这也将迫使客户端在要求它创建地区之前获得一个具体的国家。

最新更新