【问题标题】:How can an Entity validate a foreign key?实体如何验证外键?
【发布时间】:2021-05-17 20:26:34
【问题描述】:

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

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 的 CountryCode),因为这将成为循环引用。当然,如果 StateId 和 CountryCode 或相应表中的条目无效,SQL Server 将抛出 FK 约束异常,但如果可能的话希望避免这种情况。我在这个架构中做错了什么?谢谢!

【问题讨论】:

    标签: .net architecture foreign-keys entity data-access-layer


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多