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

我试图删除没有级联删除连接的行,没有帮助。可为空 - 这是问题,但我试过 - 不是结果。 –