Skip to content
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

Invalid Cast Operation #35380

Open
wbaldanw opened this issue Dec 23, 2024 · 0 comments
Open

Invalid Cast Operation #35380

wbaldanw opened this issue Dec 23, 2024 · 0 comments

Comments

@wbaldanw
Copy link

wbaldanw commented Dec 23, 2024

Hi, I found an issue when I try to run this code:
var place = await context.Places.Include(x => x.Organization).FirstOrDefaultAsync(x => x.Id == id);
InvalidCastException: Unable to cast object of type 'PlaceManagement.Place' to type 'OrganizationManagement.Organization'.

if I use AsNoTracking works fine:
await context.Places.Include(x => x.Organization).AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);

It seems to be a bug because I have a specific scenario designed to simplify record retrieval. Here's the context: I have two classes, Organization and Place, both inheriting from EntityBase. The EntityBase class includes an ID property, which is a GUID.

The database already contains Organization records, and Place is a new feature. Place and Organization have a one-to-one relationship, and Place can also be associated with Location (another entity). In this setup, the Place ID shares the same GUID as the associated Organization or Location.

Based on this structure, when I attempt to retrieve an Organization, an error is thrown.

Project: InvalidCast-EF.zip

Git Project: https://github.com/wbaldanw/ef-invalid-operation-exception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant