Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架在删除之前执行更新,我想停止此操作_C#_Asp.net_.net_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 实体框架在删除之前执行更新,我想停止此操作

C# 实体框架在删除之前执行更新,我想停止此操作,c#,asp.net,.net,asp.net-mvc,entity-framework,C#,Asp.net,.net,Asp.net Mvc,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")]

我有实体框架的问题,我有两个代码一流的国家和城市

  [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; }

}
我想阻止这一切。。如果实体框架与任何表相关,我希望实体框架拒绝删除
任何人都知道如何解决这个问题???

用下面的代码替换您的
城市
模型,您需要做的就是告诉实体
城市
存在需要
国家

[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
列。

在删除数据之前,您应检查相关性。如果存在外键依赖项,并且您试图删除表数据依赖的主键值,则会抛出错误。有两个选项,手动检查依赖项或使用实体框架查找依赖项。 对于手动检查列数据相关性,下面的语法将查找计数

using (var context = new YourDbContext())
{
    //check if the Country is not in used in City table
    var count = context.ModelNameGivenForCityDb.Count(u => u.CountryId== countryKeyToDelete);
    if(count == 0)
   {
      // code to delete
   }
}
另一个选项是在运行时使用EF查找外键依赖关系(注意,此逻辑将使您的代码依赖于数据库约束)。检查以下链接以查找外键相关性


不要将您的完整逻辑建立在实体框架FK依赖关系的基础上,您应该在删除任何值之前检查依赖关系。我将如何检查plz,因为我首先使用代码???我如何使我的完整逻辑基于实体框架FK依赖谢谢你我的主要问题解决了。。。但如果该字段不是必需的。。。我想在删除任何主键时停止将任何FK_uu更改为null。您必须告诉EntityFramework每个实体所需的关系。如果存在任何FK_uu实体框架,我希望它作为我的数据库必须提醒我。如果我忘记在实体中添加[Required],可能实体框架会使一些重要数据为空……如果我们忘记添加Required,我们就没有按照应该的方式配置模型。我们请客。在定义关系时我们必须小心。我明白了。。。谢谢:)
[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; }
}
using (var context = new YourDbContext())
{
    //check if the Country is not in used in City table
    var count = context.ModelNameGivenForCityDb.Count(u => u.CountryId== countryKeyToDelete);
    if(count == 0)
   {
      // code to delete
   }
}