我正在使用Entity Framework并且拥有包含多个EMAIL和PHONE实体的PERSON实体。更新人员时,我有一个更新地址的帮助方法和一个更新电子邮件地址的帮助方法。我无法找到一种消除它们之间所有代码重复的好方法。我的第一个想法是使用泛型,但我想不出怎么做,我不会最终得到一个过于复杂的方法,这会降低可读性,而不是增加可维护性。谢谢!
private void HandleEmailUpdate(PERSON personEntity, string emailType, string newValue)
{
var emailEntity = personEntity.EMAILs.FirstOrDefault(h => h.EMAIL_TYPE == emailType);
if (emailEntity == null)
{
if (string.IsNullOrEmpty(newValue))
return;
var newEmail = new EMAIL
{
EMAIL_TYPE = emailType,
EMAIL_ADDR = newValue,
SSN = personEntity.SSN,
PID = personEntity.PID
};
personEntity.EMAILs.Add(newEmail);
_context.Entry(newEmail).State = EntityState.Added;
}
else if (emailEntity.EMAIL_ADDR != newValue)
{
if (newValue == "")
{
_context.Entry(emailEntity).State = EntityState.Deleted;
}
else
{
_context.Entry(emailEntity).CurrentValues.SetValues(new {EMAIL_ADDR = newValue});
_context.Entry(emailEntity).State = EntityState.Modified;
}
}
}
private void HandlePhoneUpdate(PERSON personEntity, string phoneType, string newValue)
{
var phoneEntity = personEntity.PHONEs.FirstOrDefault(h => h.PHONE_TYPE == phoneType);
if (phoneEntity == null)
{
if (string.IsNullOrEmpty(newValue))
return;
var newPhone = new PHONE
{
PHONE_TYPE = phoneType,
PHONE1 = newValue,
SSN = personEntity.SSN,
PID = personEntity.PID
};
personEntity.PHONEs.Add(newPhone);
_context.Entry(newPhone).State = EntityState.Added;
}
else if (phoneEntity.PHONE1 != newValue)
{
if (newValue == "")
{
_context.Entry(phoneEntity).State = EntityState.Deleted;
}
else
{
_context.Entry(phoneEntity).CurrentValues.SetValues(new {PHONE1 = newValue});
_context.Entry(phoneEntity).State = EntityState.Modified;
}
}
}
用法:(我用'xxx'审查了名字)
HandlePhoneUpdate(entity, "ALT", updatedPerson.PhoneAlt);
HandlePhoneUpdate(entity, "CELL", updatedPerson.PhoneCellWork);
HandlePhoneUpdate(entity, "SECOND_CELL", updatedPerson.PhoneCellPersonal);
HandlePhoneUpdate(entity, "xxx", updatedPerson.Phonexxx);
HandlePhoneUpdate(entity, "HOME", updatedPerson.PhoneHome);
HandlePhoneUpdate(entity, "WORK", updatedPerson.PhoneWork);
HandleEmailUpdate(entity, "ALT", updatedPerson.EmailAlt);
HandleEmailUpdate(entity, "xxx", updatedPerson.Emailxxx);
HandleEmailUpdate(entity, "HOME", updatedPerson.EmailPersonal);
HandleEmailUpdate(entity, "xxx", updatedPerson.Emailxxx);
HandleEmailUpdate(entity, "WORK", updatedPerson.EmailWork);
答案 0 :(得分:0)
如果他们遵循相同的规则,则统一\d
和Phone
类并创建Email
类是有意义的。如果需要,Contact
类将具有Contact
属性(电子邮件,电话,...),Type
属性以及其他属性。
这样,您可以对两种类型(电子邮件和电话)使用相同的方法:Value