Entity Framework Core naviagional property does not remain null
Clash Royale CLAN TAG#URR8PPP
Entity Framework Core naviagional property does not remain null
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?
I have a lot of generic methods, so the get method gets the dog because other may want to do something with the dog.
– Thomas Koelle
14 hours ago
I'm going to take a stab at this (I could be wrong), and say the problem is probably stemming from trying to eager load (.Include(...)) a navigation property marked as virtual which means it's lazy loaded. You have to pick one. And since lazy loading is not turned on by default (because it causes weird side effects like this), unless you've opted into lazy loading, you shouldn't use the virtual keyword.
– Adam Vincent
14 hours ago
@AdamVincent you are completly right it is virtual. Thanks. I will try to work on a solution with that. Thanks
– Thomas Koelle
14 hours ago
Are you using Lazy loading proxies, i.e. has
.UseLazyLoadingProxies()
configuration call somewhere in the code? Because if you do so, you wont' be able to remove virtual
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
14 hours ago
.UseLazyLoadingProxies()
virtual
1 Answer
1
It might be creating the dog when it reads in Ann, due to the include.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Why are you including a dog while selecting? If you just need to change the name of person!
– Uttam Ughareja
14 hours ago