实体如何验证外键?

问题描述

在我的数据访问层中,我有实体程序集和存储库程序集。 在实体程序集中,我有地址类

public class Address
{
  public int AddressId {get; set;}
  public string StreetAddress {get; set;}
  public string City {get; set;}
  public int StateId {get; set;} // foreign key to State table
  public int CountryCode {get; set;} // foreign key to Country table

  public bool Validate()
  {
    // I can verify the StreetAddress and City for empty string and maxlength here
    // but how can I verify the StateId and CountryCode here?
  }
}

在引用实体程序集的存储库程序集中,我有地址存储库。我没有使用实体框架,而是使用 Dapper 进行数据库操作。

public class AddressRepository : IAddressRepository
{
  public int Create(Address address)
  {
    if (address == null) throw new ArgumentNullException(nameof(address));
    if (address.Validate())
    {
      // ... create address here ...
    }
  }
}

在上面的代码中,我的 Address 实体不能调用任何存储库方法,例如 StateRepository.Get(int stateId) 来验证 StateId(或 CountryRepository for CountryCode),因为这将成为循环引用。当然,如果 StateId 和 CountryCode 或相应表中的条目无效,SQL Server 将抛出 FK 约束异常,但希望尽可能避免这种情况。我在这个架构中做错了什么?谢谢!

解决方法

您的环境是 DI 环境吗? 如果是这样,您可以实现 IValidatableObject,然后使用 ValidationContext 对象的方法 GetService。

查看此链接以更好地理解我的意思: Validation

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...