阅读了所有SO帖子后,这个帖子最接近The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable但是我没有进行INSERT而且我没有删除任何内容(故意是,AutoMapper可能是"导致该效果")
当我尝试按如下方式更新记录时,我收到此错误。最初的INSERT工作得很好。支持班:
public class UpdateStructureInput : StructureTableModel, IInputDto
{
}
[Table("Structures", Schema = "dbo")]
public class StructureTableModel : EmEntityBase
{
#region Public Members
[ForeignKey("ParentStructureId")]
public virtual StructureTableModel ParentStructure { get; set; }
public long? ParentStructureId { get; set; }
[ForeignKey("SiteId")]
public virtual SiteTableModel Site { get; set; }
[Required(ErrorMessage = "Required.")]
public long SiteId { get; set; }
[Required(ErrorMessage = "Required.")]
public string Name { get; set; }
#endregion
}
以下是更新Name字段后生成异常的代码,并将其他所有内容保留为相同的值:SiteId = 1,ParentStructureId = null:
public void UpdateStructure(UpdateStructureInput aInput)
{
StructureTableModel structure = _StructureRepository.Get(aInput.Id);
Mapper.Map(aInput, structure);
_StructureRepository.Update(structure);
}
自动播放器定义为:
Mapper.CreateMap<UpdateStructureInput , StructureTableModel>();
更新 要求的附加代码。存储库和实体类构建在http://www.aspnetboilerplate.com/之上,所以我没有在这里包含该源,因为它可以从NuGet获得。
/// <summary>
/// Base class for all entities defined in the system. This allows for the following
/// COMMON features:
/// - Primary key "Id" of type long
/// - Auditing which adds Date & User information for creation and update
/// </summary>
public abstract class EmEntityCommon : AuditedEntity<long>
{
}
/// <summary>
/// Extends the common functionality by adding the ability to mark a record as deleted rather than
/// deleting it from the database. Unless there is a reason not to mark an entity as a soft delete
/// then all entities should descend from this class.
/// </summary>
public class EmEntityBase : EmEntityCommon, ISoftDelete
{
#region Implementation of ISoftDelete
/// <summary>
/// Used to mark an Entity as 'Deleted'.
/// </summary>
public bool IsDeleted { get; set; }
#endregion
}
public interface IStructureRepository : IRepository<StructureTableModel, long>
{
}
public class StructureRepository : EmRepositoryBase<StructureTableModel>, IStructureRepository
{
}
/ UPDATE
我猜这个由于某种原因,EF认为我在进行AutoMapper调用时会以某种方式孤立SiteId,将相同的值1分配给它?
如何解决此问题?