Entity Framework Core naviagional property does not remain null

c# entity-framework entity-framework-core

Question

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?

1
2
9/14/2018 12:59:12 PM

Accepted Answer

I just want to post an answer in case any search ends here.

It was completly correct that virtual does not matter, and the issue was in some mapping between my Dto and domain layer where I, by mistake, attached a blank entry.

0
9/17/2018 8:56:13 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow