如何解决实体如何验证外键?
在我的数据访问层中,我有实体程序集和存储库程序集。 在实体程序集中,我有地址类
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。