c# - Entity Framework 在删除前执行更新,我想停止这个

标签 c# asp.net .net asp.net-mvc entity-framework

我的 Entity Framework 有问题我有两个代码一流的国家和城市

  [Table("dbo.Countries")]
public class Country
{
    public int CountryId { get; set; }
    public string CountryNameAr { get; set; }
    public virtual ICollection<City> Cities { get; set; }
}

 [Table("dbo.Cities")]
public class City
{
    public int CityId { get; set; }
    public int CountryId { get; set; }
    public string CityNameAr { get; set; }
    public virtual Country Country { get; set; }

}

每个国家都有很多城市,,,我已经添加了一些国家和城市。 我的问题是:当我删除任何国家时,它会将城市中的 countryId 更新为 null。 我已经在 DBContext 中写道:

ModelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        ModelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

当我在 SQL Server 中跟踪它时... Entity Framework 在 cities 表中创建更新语句然后在 country 表中删除语句...

exec sp_executesql N'UPDATE [dbo].[Cities]
SET [CountryId] = NULL
WHERE ([CityId] = @0)    

exec sp_executesql N'DELETE dbo.Countries
WHERE (CountryId = @0)',N'@0 int',@0=6

我想停止这个..我希望 Entity Framework 拒绝删除如果它们与任何表相关 有人知道如何解决这个问题吗????

最佳答案

用下面的代码替换你的 City 模型,你需要做的就是告诉实体 CountryCity 所必需的> 存在:

[Table("dbo.Cities")]
public class City
{
    public int CityId { get; set; }
    public int CountryId { get; set; }
    public string CityNameAr { get; set; }
    [Required]
    public virtual Country Country { get; set; }
}

Country 声明为 Required 后,外键将不会生成为 Nullable 列。

关于c# - Entity Framework 在删除前执行更新,我想停止这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39826280/

相关文章:

c# - 使用 Entity Framework 的 Asp.net GridView 搜索

c# - 下拉列表不选择值 asp.net

c# - 如何以编程方式创建 MSI 安装程序?

.net - 是否可以在 VS2012 中将 Entity Framework 设计器与 SQLite 一起使用?

c# - 数据驱动的单元测试问题

c# - 什么时候推荐在 NHibernate 中使用二级缓存

c# - 事件未触发 SharePoint DataGrid 中的动态列

c# - 关闭窗口返回结果

asp.net - IdentityServer3 仅在移动设备上登录时持续重定向

c# - 在不锁定文件的情况下将 BitmapFrame 用于元数据