简体   繁体   中英

Why is Entity Framework 5 code-first not mapping my enum property?

I have an MVC3 project using EF5 targeting ASP.NET framework 4.5 that I'm updating with some additional classes. One of my new classes has a nullable, nested enum property that is not being mapped to the database.

public class MyProblemClass
{
  public MyClass.MyEnum? MyPropertyName { get; set; }
}

Here are some of the relevant details:

  • The code generated by running Add-Migration doesn't contain this property.
  • I have created other new classes with basic enums that are mapped correctly.
  • I have other existing classes with nested enums that are mapped correctly.
  • If I put a basic enum in the problem class it maps correctly.
  • If I put the problem enum in a different class it doesn't work there either.

By basic enums I mean ones that are defined outside of a class:

namespace My.Project.NewStuff
{
  public enum MyEnum
  {
    Option1,
    Option2
  }
}

By nested enums I mean ones that are defined inside of a class:

namespace My.Project.NewStuff
{
  public static class MyClass
  {
    public enum MyEnum
    {
      Option1,
      Option2
    }
    public static string MyExtensionMethod (this MyEnum option) {...}
  }
}

The new enum and class names are actually identical to an existing working one, but in a different namespace. The new one has slightly different options, and different code in the extension methods.

I have tried slightly renaming the class, enum and property to see if there are any bugs related to using the same name, but this didn't help.

What could be preventing my nested enum property from being mapped to the database?

Solution: rename the enum to something unique. As per this SO answer , Entity Framework doesn't support multiple classes with the same unqualified name. This appears to include enums.

Normally you would get an error similar to the following during the Add-Migration step:

Schema specified is not valid. Errors:

The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'MyEnum'.

However, if the enumerators in the conflicting types are not identical, the Add-Migration doesn't show this error, and simply generates a migration that omits mapping any properties of the conflicting type. Making the enumerators identical in the conflicting types will reveal the error again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM