我有一个与删除有关的异常问题。我的模型包括一个联系表。联系人可能有deer_contacts_info或livestock_contacts_info。 SQL express选项设置为“no action”,换句话说,如果共享数据在其他表中有任何子行,则阻止共享数据被删除。如果有鹿或牲畜数据,它不会删除。 SQL express选项设置为“no action”,换句话说,如果共享数据在其他表中有任何子行,则阻止共享数据被删除。
示例:
此方案在MVC Web应用程序中正常工作。奇怪的是,测试项目没有产生正确的结果。
示例:
以下是控制器删除方法的代码段:
if (contactType == Globals.getLivestockType())
try
{
livestock_contacts_info livestock_contacts_info = db.livestock_contacts_info.Find(id);
if (livestock_contacts_info != null)
{
db.livestock_contacts_info.Remove(livestock_contacts_info);
db.SaveChanges();
}
}
catch (Exception)
{
CSession["message"] = "Error deleting livestock information for contact_id" + id;
return RedirectToAction("ListContacts");
}
else if (contactType == Globals.getDeerFarmType())
try
{
deer_contacts_info deer_contacts_info = db.deer_contacts_info.Find(id);
if (deer_contacts_info != null)
{
db.deer_contacts_info.Remove(deer_contacts_info);
db.SaveChanges();
}
}
catch (Exception)
{
CSession["message"] = "Error deleting deer contact information for contact_id" + id;
return RedirectToAction("ListContacts");
}
/* after deleting subject specific data, attempt to delete shared data. Shared data will not be deleted
If it has any subject data remaining.
*/
try
{
contact contact = db.contacts.Find(id);
if (contact == null)
{
CSession["message"] = "contact " + id + " doesn't exist";
}
else
{
db.contacts.Remove(contact);
db.SaveChanges();
}
return RedirectToAction("ListContacts");
}
我查看了联系人的定义,试图了解发生了什么。这是:
public partial class contact
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CONTACT_ID { get; set; }
[RegularExpression("^[^;]{0,100}$", ErrorMessage="This text field has unacceptable characters")] /* ; not allowed */
public string FIRST_NAME { get; set; }
public string MIDDLE_NAME { get; set; }
public string LAST_NAME { get; set; }
public string BUSINESS_NAME { get; set; }
public string ADDRESS1 { get; set; }
public string ADDRESS2 { get; set; }
public string CITY { get; set; }
public string STATE { get; set; }
public string ZIP_CODE { get; set; }
public string COUNTRY { get; set; }
public string TELEPHONE1 { get; set; }
public string TELEPHONE2 { get; set; }
[RegularExpression("^[0-9-]{0,10}$", ErrorMessage="Please use only digits and dashes, with a maximum length of 10")]
public string CELL_PHONE { get; set; }
[EmailAddress]
public string EMAIL_ADDRESS { get; set; }
public string COMMENTS { get; set; }
public virtual deer_contacts_info deer_contacts_info { get; set; }
public virtual livestock_contacts_info livestock_contacts_info { get; set; }
}
代码片段首先删除鹿场和牲畜数据,然后共享联系人。在代码的共享联系人删除部分中,我比较了两个测试的类内容:对于Web MVC测试,deer_contacts_info
和livestock_contacts_info
都为空。但是,测试项目测试具有非null内容。然后我修改了代码,使它们都为null。结果没有改变:测试项目进行级联删除。你有什么想法吗?