Giter Site home page Giter Site logo

Using SmartEnum with EF about smartenum HOT 7 CLOSED

ardalis avatar ardalis commented on May 14, 2024
Using SmartEnum with EF

from smartenum.

Comments (7)

yannduran avatar yannduran commented on May 14, 2024 1

@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.

CindyKee avatar CindyKee commented on May 14, 2024 1

Thanks for the tip, @yannduran! I will take a look at using this trick in the future!

from smartenum.

trevor-hackett avatar trevor-hackett commented on May 14, 2024

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.

ardalis avatar ardalis commented on May 14, 2024

Can you share some code, either here or in a gist?

from smartenum.

CindyKee avatar CindyKee commented on May 14, 2024

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.

CindyKee avatar CindyKee commented on May 14, 2024

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.

CindyKee avatar CindyKee commented on May 14, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.