I have two related tables:

public class InspectionItems { [Key] public int InspectionItemID { get; set; } ......... [StringLength(10)] public string QualiteGradeID { get; set; } [ForeignKey("QualiteGradeID")] public virtual QualityGrades QualityGrades { get; set; } } public partial class QualityGrades { [Key] [StringLength(10)] public string QualiteGradeID { get; set; } [Required] [StringLength(100)] public string Title { get; set; } } InspectionItems inspectionItem = _unitOfWork.InspectionItems.All().FirstOrDefault(it => it.InspectionItemID == item.Id); if (inspectionItem != null) { inspectionItem.QualiteGradeID = "RR"; _unitOfWork.InspectionItems.Update(inspectionItem); _unitOfWork.Commit(); } public override void Update(T entity) { if (entity == null) { throw new ArgumentException("Cannot update a null entity."); } _dbSet.Local.Clear(); _dbSet.Attach(entity); _dbContext.Entry(entity).State = EntityState.Modified; } 

I need to update the QualiteGradeID field of the InspectionItems table, the problem is that this field may be NULL in the database, and when I try to update it, I generate SQL:

  UPDATE [dbo].[InspectionItems] SET [QualiteGradeID] = NULL WHERE ([InspectionItemID] = @1 ) 

I make an experiment: I prohibit NULL values ​​in the QualiteGradeID field (the InspectionItems table) - and everything starts working. Maybe someone faced with such behavior, I will be very grateful for the help.

  • @Vladimirr; If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

1 answer 1

You cannot set the ID, because QualityGrades is not loaded into Local. Either install the navigation one yourself, or add the inspectionItem Include c QualityGrades to the selection request.

Do you use UnitOfWork to use DI for tests?

If not, I recommend that you abandon UnitOfWork and all kinds of repositories. The link is the answer in which a person explains that it is all from the evil one)))

https://codereview.stackexchange.com/questions/47879/unit-of-work-and-repository-with-entity-framework-6

PS And why do you clean the Local, and then attach the object?

  • removed _dbSet.Local.Clear (); _dbSet.Attach (entity); from Update () functions and it all worked. Probably you are right when I call Local.Clear () the connection with the QualityGrades table is lost, and since the updated field has an FK connection with the QualityGrades table, EF does not understand the correct value whether it inserts into the table or not. - Vladimirr