0

請大家幫忙。我的EntityFramework 6.有無實體工作:實體框架6:刪除多個父項的子項

public class PowerStation { 

     public Guid PowerStationId { get; set; } 
     public string Name { get; set; } 

     public Guid PowerStationTypeId { get; set; } 
     public virtual PowerStationType PowerStationType { get; set; } 

     public Guid SubjectId { get; set; } 
     public DateTime SubjectTransactionTime { get; set; } 
     public virtual Subject Subject { get; set; } 

     public Guid ParticipantOremId { get; set; } 
     public DateTime ParticipantOremTransactionTime { get; set; } 
     public virtual ParticipantOrem ParticipantOrem { get; set; } 

     public Guid? DcId { get; set; } 
     public DateTime? DcTransactionTime { get; set; } 
     public virtual Dc Dc { get; set; } 

     public virtual ICollection<Equipment> Equipments { get; set; } 
     public virtual ICollection<DcLink> DcLinks { get; set; } 
     public virtual ICollection<DcPowerStationProposal> DcPowerStationProposals { get; set; } 
} 

我嘗試刪除這個實體,但得到的異常:

操作失敗:關係不能被改變,因爲 一個或多個外鍵屬性不可空。當 更改爲關係時,相關的外鍵屬性 設置爲空值。如果外鍵不支持空值,則必須定義一個新的關係,外鍵屬性必須爲 分配另一個非空值,或者無關對象必須爲 刪除。

我可以試試這個:

entity = db.PowerStations 
        .Include(x => x.Equipments) 
        .Include(x => x.DcLinks) 
        .Include(x => x.DcPowerStationProposals) 
        .FirstOrDefault(x => x.PowerStationId == entity.PowerStationId && x.TransactionTime == entity.TransactionTime); 


var station = db.ParticipantOrems.FirstOrDefault(x => x.ParticipantOremId == entity.ParticipantOremId 
       && x.TransactionTime == entity.ParticipantOremTransactionTime); 
       station.PowerStations.Remove(entity); 

var subject = db.Subjects.FirstOrDefault(x => x.SubjectId == entity.SubjectId 
       && x.TransactionTime == entity.SubjectTransactionTime); 
       subject.PowerStations.Remove(entity); 

var dc = db.Dcs.FirstOrDefault(x => x.DcId == entity.DcId 
       && x.TransactionTime == entity.DcTransactionTime); 
       dc.PowerStations.Remove(entity); 

var type = db.PowerStationTypes.FirstOrDefault(x => x.PowerStationTypeId == entity.PowerStationTypeId); 
       type.PowerStations.Remove(entity); 

db.Equipments.Local.Where(x => x.PowerStation == null).ToList().ForEach(r => Equipments.Remove(r)); 
db.DcLinks.Local.Where(x => x.PowerStation == null).ToList().ForEach(r => DcLinks.Remove(r)); 
db.PowerStationProposals.Where(x => x.PowerStation == null).ToList().ForEach(r => DcPowerStationProposals.Remove(r)); 

回答

0

如果你想刪除全部投運應刪除遷移和reupdate它

+0

我要在數據庫中刪除行,不表。 –

+0

我沒有檢查代碼,但它說你的表與外鍵連接了其他表,並且它們不可爲空,使它們可爲空或刪除連接的行? – minoset

+0

我試圖刪除沒有級聯刪除連接的行,沒有幫助。可爲空 - 這是問題,但我試過 - 不是結果。 –