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

Behavior of ToString on enums in query #3347

Open
stiankroknes opened this issue Nov 4, 2024 · 2 comments
Open

Behavior of ToString on enums in query #3347

stiankroknes opened this issue Nov 4, 2024 · 2 comments

Comments

@stiankroknes
Copy link

When mapping enums to enum types in Postgres as described here:

The ToString on a mapped enum in query select is translated, and we get the Postgres enum type text.
I expected this configuration to be transparent to the application and just a storage concern, but it affects the application code due to the changed behavior.

Should the documentation on the enum configuration mention this?

I am not stating that this is wrong behavior, just that it could easily be overlooked when starting to use enum types.

The translation was probably introduced here.

@roji
Copy link
Member

roji commented Nov 5, 2024

I'm not sure I understand - you're proposing to document that when ToString() is called on an enum in a LINQ query, that's translated to a cast to PG text? What other behavior would you expect here, and how is this different from applying ToString() on any other type (e.g. an int)?

@stiankroknes
Copy link
Author

When we use MapEnum the behavior of the ToString() method in a LINQ query changes.

public enum Color { Red = 1, Green, Blue , ..}
public class Entity {
   public Color Color { get; set; }
}

Without MapEnum:

  • Calling ToString() on the C# enum within a LINQ query translates to the enum's string representation as defined in the C# code. For example, assume entity has color red, then entitity.Color.ToString() would return "Red" not the integer value stored in database.

With MapEnum:

  • Calling ToString() on the mapped enum within a LINQ query translates to the enum's text value in the database. For example, if Colors is mapped to a Postgres enum and entity.Color.ToString() is called in a LINQ query, it will return the text "red" (entity color is red as above example).

This change in behavior can be unexpected for developers who assume that MapEnum is purely for storage purposes.

var data = db.Entities.Select(t => t.Color.ToString()).ToList();
// without MapEnum
// data = [ "Red", "Green", "Blue" ,..]
// with MapEnum
// data = [ "red", "green", "blue" ,..]

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

No branches or pull requests

2 participants