- VS2013, EF6
Having read all the SO posts this one comes closest The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable but I am not doing an INSERT and I am not DELETING anything (deliberately that is, AutoMapper may be "causing that effect")
I am getting this error when I attempt to UPDATE a record as follows. The initial INSERT works just fine. The supporting classes:
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
}
and here is the code that generates the exception after I have updated the Name field and left everything else the same viz: SiteId = 1, ParentStructureId = null:
public void UpdateStructure(UpdateStructureInput aInput)
{
StructureTableModel structure = _StructureRepository.Get(aInput.Id);
Mapper.Map(aInput, structure);
_StructureRepository.Update(structure);
}
The automapper is defined as:
Mapper.CreateMap<UpdateStructureInput , StructureTableModel>();
UPDATE Additional code as requested. The repository and entity classes are built on top of http://www.aspnetboilerplate.com/ so I have not included that source here as it is available from 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
I am guessing that for some reason EF believes that I have somehow orphaned SiteId when I do the AutoMapper call to assign the same value of 1 back to it?
How do I get around this issue?