在插入或更新数据库之前验证forein键是否正确? [英] Is it right approach to validate forein key before you do insert or update to database
问题描述
这是一种正确的方法,是否有逻辑来验证Master Table中是否存在ForeignKey值?
表:员工
字符串名称{get; set;}
string年龄{get; set;}
int AddressID {get; set;} // Fk - 地址表
int CountryCode {get; set;} // Fk - 国家表
新员工插入操作
示例AddressID = 100& CountryCode = 10
如果(sql.exists(AddressTable.contains(100))有效则无效
if(sql.exists(Country) .Contains(10))有效无效
如果所有数据都有效,那么请插入/更新
谢谢,
我尝试过:
DatAnnotation / CustomAttributes,
Hi,
Is it a right approach have logic to validate ForeignKey values exists in Master Table or not?
Table : Employee
string Name{get;set;}
string Age{get;set;}
int AddressID{get;set;} //Fk - Address table
int CountryCode{get;set;} // Fk - Country Table
New Employee Insert Operation
Example AddressID=100 & CountryCode=10
If(sql.exists(AddressTable.contains(100)) valid else invalid
if(sql.exists(Country.Contains(10)) Valid else invalid
If all data valid then do Insert/Update
Thanks,
What I have tried:
DatAnnotation / CustomAttributes,
推荐答案
这取决于验证失败的可能性。如果这是一个不太可能的边缘情况,那么我不会打扰,我会通过传统的异常处理。如果验证可能会失败,您可能希望在插入之前明确验证。
It depends on the likelihood that the validation is going to fail. If it is an unlikely edge case then I wouldn't bother, I'd handle this via traditional exception handling. If it's likely that the validation is going to fail you might want to validate explicitly before inserting.
这篇关于在插入或更新数据库之前验证forein键是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!