我想知道我们是否想检查是否在db中添加了新项,projectId是否存在于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?如果创建集成测试,如:
[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中。管理这张支票的最佳地点是哪里?致以敬意,
发布于 2021-10-12 13:36:28
最简单的方法是请求将国家对象提供给地区的构造者:
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从国家存储库中检索有效的国家,那么当获得一个空国家时,您的构造将抛出。
或者,将CountryId保留为区域上的构造函数参数,将区域构造函数设置为内部构造函数,使其不能在域外创建,然后使Country对象成为地区工厂:
public class Country
{
public District CreateDistrict(string name)
{
return new District(name, this.Id);
}
}这也将迫使客户得到一个具体的国家,然后要求它创建地区。
https://stackoverflow.com/questions/69536687
复制相似问题