I have a class with a linked class, as example imagine a Person with a Dog. It is mapped like this in the PersonDto:
public int? DogId { get; set; }
public virtual DogDto Dog { get; set; }
For many persons the DogId is null, but after I change something in Person and do a SaveChanges then entity framework insist that it should insert a blank entry.
My scenario is a lot bigger but simplified it could look like this:
var person = await _entities.Persons.Where(p => p.Name == "Ann")
.Select(p => p).Include(p => p.Dog).First();
person.Name = "Bob";
_entities.SaveChanges();
Imagine now that Ann does not have a dog, and DogId should remain null.
The SQL Entity Framework Core does an INSERT like this:
DECLARE @inserted0 TABLE ([Id] int, [_Position] [int]);
MERGE [Dogs] USING (
VALUES (@p0, @p1, @p2, @p3, @p4, 0),
(@p5, @p6, @p7, @p8, @p9, 1)) AS i ([Col1], [Col2], [Col3], [Col4], [Col5],
_Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([Col1], [Col2], [Col3], [Col4], [Col5])
VALUES (i.[Col1], i.[Col2], i.[Col3], i.[Col4], i.[Col5])
OUTPUT INSERTED.[Id], i._Position
INTO @inserted0;
What am I missing. Wouldn't int? be enough to allow it to be null?
.UseLazyLoadingProxies()
configuration call somewhere in the code? Because if you do so, you wont' be able to removevirtual
from the navigation property. Also can the issue be reproduced with your "simplified example"? Because if yes, then it's EF Core bug. – Ivan Stoev Sep 14 '18 at 13:39virtual
keyword should have no effect if lazy loading is not being used. I'm almost certain I've seen exactly that written in the documentation. But since removing the virtual keyword resolved the issue, there may be an oversight somewhere. – Adam Vincent Sep 14 '18 at 17:56