-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Shadow property for Primary Key - exception 'No backing field could be found' #28154
Comments
This looks like a bug generating queries with shadow primary keys. The entity quality evaluates to PK equality, but there is then an attempt to access a CLR property for the PK when it does not exist. /cc @smitpatel @maumar Model:
|
Notes from triage: var hasPersistedOtherQuestions = context.Questions.Any(q => q != nameQuestion); In general, this query cannot be made to work with shadow primary keys because the CLR object itself does not have access to the shadow key. It could, perhaps, be made to work if As a workaround, the unique identity of the domain object can be used, since this is, of course, carried with the CLR object: var hasPersistedOtherQuestions = context.Questions.Any(q => q.QuestionId != nameQuestion.QuestionId); |
@ajcvickers: // act & assert
using (var context = new DatabaseContext())
{
var nameQuestion = context.Questions.SingleOrDefault(q => q.QuestionId == nameQuestionId);
// throws exception
var hasPersistedOtherQuestions = context.Questions.Any(q => q != nameQuestion);
Assert.True(hasPersistedOtherQuestions);
} |
@skbtomek Yes, but what I was trying to say is that even though in a case like this where it could be made to work, the complexity and cost is not worth the value, so we're not going to do so. Especially since it would be a special-case solution for tracking queries only. Generally speaking, putting primary keys in shadow state is a pit-of-failure. It's possible, but not something we would ever recommend. |
What I would like to achieve?
To have separate domain model identifier (GUID) from database primary key (long).
Domain model
Db context:
Use case
Test below fails by throwing exception on:
context.Questions.Any(q => q != nameQuestion)
Exception
Potential solutions that I would like to avoid
Solution 1
Adding private property long _id to Question model
Solution 2
Querying by domain QuestionId instead of relying on reference equality:
Unfortunately, it's easy to forget about it in new queries.
Full project source code
efcore-shadow-pk.zip
Provider and version information
EF Core version: 6.0.5
Database provider: (Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (net6.0)
The text was updated successfully, but these errors were encountered: