Comments (7)
@desertrambler Personally in cases like this I'd be using a lookup table in the database. Although, as Steve's article shows, you can map a complex type etc, with LINQ to Entities (L2E) you will have problems in code that uses lambdas, such as filtering or comparing etc.
To alleviate your problem, you could simply declare a local variable in any method that's using L2E where you want to use a SmartEnum value, assigning them the SmartEnum's Value.
Then use the variable in the code in place of the SmartEnum.
This Won't Work
// using a SmartEnum's Value in a L2E statement
var role = db.Roles.FirstOrDefault(r => r.ID == Role.Author.Value); // not OK
This Would Work
// still using a SmartEnum, but supplying the Value value to the L2E statement as an integer
var authorRole = Role.Author.Value;
var role = db.Roles.FirstOrDefault(r => r.ID == authorRole); // OK
Yes, it's a little bit of a pain, but that's just a "quirk" of L2E. If you're not supplying something that L2E can understand (ie "an entity's property"), then the value that you're using to filter with has to be a primitive type.
HTH
from smartenum.
Thanks for the tip, @yannduran! I will take a look at using this trick in the future!
from smartenum.
In my opinion, it doesn't make sense to have a default constructor. Enumerations aren't meant to be created on the fly. The static instances should be used (possibly by using the FromValue()
methods) instead of having a new instances created.
from smartenum.
Can you share some code, either here or in a gist?
from smartenum.
I was following the @ardalis article here: https://ardalis.com/persisting-the-type-safe-enum-pattern-with-ef-6
And the sample code there creates a default constructor so that the type-safe-enum can be used in an entity class with EF:
private Role()
{
// required for EF
}
So what I decided to do was copy the SmartEnum class from this repo instead of using the NuGet package and add a default constructor as in this gist:
https://gist.github.com/desertrambler/4758d69b649e97d1b7b3310ebabcab23
Then when I add this to my DbContext class's OnModelCreating
method, it doesn't throw compile errors:
modelBuilder.Entity<AuditLogItem>()
.Property(a => a.Action.Value)
.HasColumnType("int");
modelBuilder.ComplexType<AuditActionType>()
.Ignore(a => a.Name);
Now, I haven't tried using this at runtime yet - this was just to get past the compile errors.
Are there other issues I am going to have when I try to run this?
from smartenum.
So I am running into issues now. I want my entity class to have a property as such:
public AuditActionType Action { get; set; }
That maps to an existing column in the database called Action
that is already an INTEGER
column (from when Action
was a primitive enum).
But the OnModelCreating
code is referencing a property called .Property(a => a.Action.Value)
and this is throwing an error:
The property 'Value' is not a declared property on type 'AuditActionType'.
Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation.
Make sure that it is a valid primitive property.
How do I fix this so I can still use this SmartEnum with EF?
from smartenum.
The error was being thrown from the Unity resolver for some reason. After double-checking all my code and doing a clean build, I got past that error. And for the most part, my SmartEnum class with the default constructor was working fine.
But then in another section of the application, they are doing dynamic LINQ to Entities and I was getting an error trying to do anything with the SmartEnum except reference its value, since that's all the DbContext
knows about. If I referenced the Name property, then I got an error because it was not mapped into the context (because it was explicitly ignored by modelBuilder.ComplexType<AuditActionType>().Ignore(a => a.Name);
). The LINQ to Entities expression evaluator can only handle entity members, navigation properties (to other entities), and initializers. And since this was a Complex Type, not an Entity, it wasn't going to work the way I needed it to. The problem the primitive enum was causing me was essentially back with the SmartEnum, just in a different way. So I had to abandon this solution and opt for a different solution.
Thanks for listening. I'll close this issue (and if there is a way to delete an issue, you are welcome to do that.)
from smartenum.
Related Issues (20)
- Deserialization of appsettings.json via ConfigurationBuilder doesn't work HOT 1
- EF Core 7 InMemory - Throwing System.ArgumentException with any query involving a SmartEnum HOT 3
- README Example does not compile
- Case Insensitive String Enum HOT 1
- Enable Discussions for repo
- Loading SmartEnum from Entity Framework without specifying it as a static property
- Not compatible with .Net 6 HOT 1
- SmartFlagEnum does not support values larger than int.MaxValue HOT 1
- Need simple method to get single int value from existing IEnumerable<MyFlagEnum>. HOT 5
- SmartEnum binding to [FromQuery] parameters HOT 3
- Ordering the values
- Can/should SmartEnum implement the non-generic IComparable interface?
- SmartEnumStringComparer not included in 7.0.0 version HOT 2
- Add a ValidationAttribute to Validate Model Property Against SmartEnum Names
- ushort error in SmartFlagEnumValueConverter HOT 1
- For the README.md I found out that the path for TestEnum.cs is broken HOT 1
- Add Description attribute HOT 1
- Please Release Version for .NET 8.0 HOT 3
- Are you open to a PR for a nullable `Name`? HOT 2
- Add a way to enumerate over the List to prevent allocation every time List is called HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from smartenum.