首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何管理Guard.Against.NotFound for IAggregateRoot

如何管理Guard.Against.NotFound for IAggregateRoot
EN

Stack Overflow用户
提问于 2021-10-12 07:34:38
回答 1查看 126关注 0票数 1

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

代码语言:javascript
复制
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?如果创建集成测试,如:

代码语言:javascript
复制
[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中。管理这张支票的最佳地点是哪里?致以敬意,

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-12 13:36:28

最简单的方法是请求将国家对象提供给地区的构造者:

代码语言:javascript
复制
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对象成为地区工厂:

代码语言:javascript
复制
public class Country
{
    public District CreateDistrict(string name)
    {
        return new District(name, this.Id);
    }
}

这也将迫使客户得到一个具体的国家,然后要求它创建地区。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69536687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档