2016-10-03 25 views
1

我有問題,實體框架我有兩個代碼一流的國家和城市實體框架刪除前執行更新,我想停止這種

[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服務器...實體框架作出更新語句在城市則表中的國家表中刪除聲明...

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 

我想要停止這..我想實體框架拒絕刪除,如果他們是任何與任何表fk_相關 任何人知道如何解決這個問題?

+0

不要根據實體框架FK依賴你的完整的邏輯,你要刪除的任何值之前檢查的依賴。 – GauravKP

+0

我將如何檢查PLZ,因爲我先使用代碼? 我如何使我的完整邏輯基於實體框架FK依賴 – Ayman

回答

1

在刪除數據之前,您應檢查依賴關係。如果存在外鍵相關性,並且您嘗試刪除表數據所依賴的主鍵值,它將拋出錯誤。有兩個選項,手動檢查依賴關係或使用實體框架查找依賴關係。 要手動檢查列數據依賴性,下面的語法將查找計數。

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來查找外鍵關聯(注意這個邏輯會使你的代碼依賴於數據庫約束)。檢查以下鏈接找到外鍵依賴

Read foreign key metadata programatically with Entity Framework 4

2

替換您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; } 
} 

聲明CountryRequired,外鍵韓元后將不會生成爲Nullable列。

+0

謝謝我的主要問題已解決... 但是,如果該字段不是必需的...我想停止將任何FK_更改爲空當刪除任何主鍵.. – Ayman

+0

您必須告知EntityFramework關於每個實體的必需關係。 – sachin

+0

我想要它作爲我的數據庫,如果有任何FK_實體框架必須提醒我。如果我忘記將[Required]放在entitiy中,實體框架將爲我刪除一些重要數據... – Ayman