【发布时间】:2017-07-25 08:43:02
【问题描述】:
请帮忙。我使用 EntityFramework 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));
【问题讨论】:
标签: c# entity-framework ef-code-first entity-framework-6 code-first