我想知道如果数据库中存在projectId,我们是否要检查是否添加新项目,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 是否存在于数据库中?如果创建集成测试的示例,例如:
[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 是否存在于数据库中。管理此检查的最佳地点在哪里?问候,