【发布时间】:2014-02-03 08:47:19
【问题描述】:
我有一个带有 EntityFramework Code First 的 Asp.Net MVC 5 网站。在我的站点中,我有一个 Restaurant 模型,其代码如下:
public class Restaurant
{
[Required]
public string Name { get; set; }
//....
public virtual IList<RestaurantType> Types { get; set; }
}
RestaurantType 的代码是:
public class RestaurantType
{
[Key]
public int ID { get; set; }
[Required]
public string Type { get; set; }
public virtual Restaurant Restaurant { get; set; }
}
当我尝试从上下文中删除 restaurant 时,我收到以下错误:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.RestaurantTypes_dbo.Restaurants_Restaurant_ID". The conflict occurred in database "aspnet-Test-20131111052251", table "dbo.RestaurantTypes", column 'Restaurant_ID'.
The statement has been terminated.
我有生产中的数据,我想尽可能安静地处理它。我尝试了以下代码:
for (int i = 0; i < restaurant.Types.Count; i++)
{
var type = restaurant.Types[i];
db.RestaurantTypes.Remove(type);
restaurant.Types.Remove(type);
}
db.Restaurants.Remove(restaurant);
await db.SaveChangesAsync();
但我得到了同样的错误。我检查了数据库,没有包含餐厅 ID 的行。我什至试过这个:
var list = db.RestaurantTypes.Where(t => t.Restaurant == null || t.Restaurant.ID == restaurant.ID);
foreach (var ib in list)
{
db.RestaurantTypes.Remove(ib);
}
db.SaveChanges();
它也没有工作。我有办法用 C# 代码解决这个问题吗?
【问题讨论】:
-
为什么餐厅有餐厅类型列表?可以是多种类型吗?另外,为什么餐厅类型会引用餐厅?
-
@TimSchmelter 餐厅有一个类型列表,是的。将其视为某种类别。例如,一家餐厅既可以是意大利餐厅,也可以是印度餐厅!我们的系统需要它。起初对
restaurant的引用不可用。我刚刚添加了它来编写最后一个sn-p。 (检查Restaurant字段是否为NULL)无论它是否存在,我都会收到错误。
标签: c# asp.net sql-server asp.net-mvc entity-framework