我的 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
模型,你需要做的就是告诉实体 Country
是 City
所必需的> 存在:
[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/