0

I'm using EF Core 2.2.4 and I'm running into very strange behavior.

Given the following code snippet:

var warrantyRegistrationId = warrantyRegistration.Id;  // warrantyRegistration.Id = 20

var order = ctx.Orders  // Id = 13
    .Where(x => x.CompanyId == 1 && x.CustomerId == warrantyRegistrationModel.CustomerId && x.IsDeleted == false && x.WarrantyRegistrationId == null)
    .FirstOrDefault();

var originalOrder = ctx.Orders    // Id = 12
    .Where(x => x.Id == order.OriginalOrderId)
    .FirstOrDefault();

order.WarrantyRegistrationId = warrantyRegistrationId; // order.WarrantyRegistrationId = 20
originalOrder.WarrantyRegistrationId = warrantyRegistrationId;  // originalOrder.WarrantyRegistrationId = 20
ctx.SaveChanges();  

// order.WarrantyRegistrationId = null, originalOrder.WarrantyRegistrationId = 20

Somehow the first assignment order.WarrantyRegistrationId = warrantyRegistrationId; is being set to null in the database.

When I run Sql Server profiler, I see the following:

exec sp_executesql N'SET NOCOUNT ON;
UPDATE [Orders] SET [WarrantyRegistrationId] = @p0
WHERE [Id] = @p1;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 int',@p1=12,@p0=20

and

exec sp_executesql N'SET NOCOUNT ON;
UPDATE [Orders] SET [WarrantyRegistrationId] = @p0
WHERE [Id] = @p1;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 int',@p1=13,@p0=NULL

I'm stuck and can't figure out why this is happening.

Any ideas?

1 Answer 1

1

In case anybody else runs into this, here's the answer.

I had set this as .HasOne().WithOne(), which created a unique index on WarrantyRegistrationId. Since I was assigning a new Id, it was removing it from the previous WarrantyRegistrationId to keep it unique.

I changed this to .HasOne().WithMany() and it's working now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.