我有一个EF Code First配置:
public class TaskLocationConfiguration : IEntityTypeConfiguration<TaskLocation>
{
public void Configure(EntityTypeBuilder<TaskLocation> b)
{
b.HasOne(x => x.TaskHeader)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x => x.TaskHeaderId);
b.HasOne(x => x.SubArea)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x=>x.SubAreaId)
.IsRequired(false);
b.HasOne(x => x.Workcenter)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x => x.SubAreaId)
.IsRequired(false);
}
}
类:
public class TaskLocation
{
public int Id { get; set; }
public int TaskHeaderId { get; set; }
public TaskHeader TaskHeader { get; set; }
public SubArea SubArea { get; set; }
public int? SubAreaId { get; set; }
public Workcenter Workcenter { get; set; }
public int? WorkcenterId { get; set; }
}
当我试图插入到表与SubAreaId仅或与WorkcenterId仅我得到一个错误:
var location = new TaskLocation()
{
CreateDate = DateTime.Now,
WorkcenterId = workcenterId,
TaskHeaderId = task.Id,
};
_context.Add(location);
错误:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_T_Locations_Workcenters_SubAreaId". The conflict occurred in database "DB_NAME", table "dbo.Workcenters", column 'Id'. The statement has been terminated.
SubAreaId和WorkcenterId应该是可选的…我的配置有什么问题?
正确配置
b.HasOne(x => x.TaskHeader)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x => x.TaskHeaderId);
b.HasOne(x => x.SubArea)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x=>x.SubAreaId)
.IsRequired(false);
b.HasOne(x => x.Workcenter)
.WithMany(x => x.TaskLocations)
.HasForeignKey(x => x.WorkcenterId) //<---- was SubAreaId here before
.IsRequired(false);