americanslon
americanslon

Reputation: 4298

Set navigation property to null EF 6

I have two entities Inspection and User

An Inspection has an Approver property which is a User hooked up like so public virtual User Approver { get; set; }

Sometimes Approver has to be set to null

I am doing it as follows

 Inspection rtrn = Context.Inspections.Where(x => x.Id == inspId).SingleOrDefault();
 rtrn.Approver = null;
 rtrn.ApprovalDate = new DateTime();

 base.Update(rtrn); //EF repo

The problem is that this does not set Approver_Id to null in the database. In fact if I put a break point at the rtrn.ApprovalDate = new DateTime(); I can see that rtrn.Approver is still of type User. It looks as if it's ignoring the rtrn.Approver = null; line all together.

At the higher level I just want to break Inspection -- User association without deleting either entity.

Thank you!

Upvotes: 1

Views: 860

Answers (1)

Arwin
Arwin

Reputation: 1023

Your virtual property is just that, virtual. It is filled with the record that matches its corresponding foreign key, which is typically ApproverId (unless you specified a different ForeignKey with the ForeignKey attribute).

If you want to get rid of the Approver, then you just need to set the ApproverId to null.

Upvotes: 1

Related Questions