ModelValidationException: Name 'AnonymousUID' cannot be used in type 'CodeFirstDatabaseSchema.AnonymousUID'

.net, c#, entity-framework, orm

Solution

As I guessed at in the comment above, change the column name to start with a lowercase 'a'

...HasColumnName("anonymousUID");

Let's hope this is a pre release defect and is fixed in the RTM ;-)

Problem

I am using Entity Framework to model an existing database. One of the database tables contains a column with the same name as the table, AnonymousUID. I use the Entity Framework Power Tools function Reverse Engineer Code First to generate the model classes and mappings. The reverse engineering procedure automatically renames the `AnonymousUID` class member (to `AnonymousUID1`) to avoid that a member name is the same as the class name. The generated model class thus looks like this: ``` public partial class AnonymousUID { public string UID { get; set; } public string AnonymousUID1 { get; set; } } ``` and the EF mapping constructor is implemented like this: ``` public AnonymousUIDMap() { // Primary Key this.HasKey(t => t.UID); // Properties this.Property(t => t.UID).IsRequired().HasMaxLength(64); this.Property(t => t.AnonymousUID1).IsRequired().HasMaxLength(64); // Table & Column Mappings this.ToTable("AnonymousUID"); this.Property(t => t.UID).HasColumnName("UID"); this.Property(t => t.AnonymousUID1).HasColumnName("AnonymousUID"); } ``` The database context class is implemented like this: ``` public partial class MyDbContext : DbContext { // Constructors... public DbSet<AnonymousUID> AnonymousUIDs { get; set; } ... protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new AnonymousUIDMap()); ... } } ``` This is all good and well, and the code builds without problems. But when I try to access arbitrary contents of the database: ``` using (var context = new MyDbContext()) { var foos = from foo in context.Foos select foo; ... } ``` the following exception is nonetheless thrown: ``` System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation: \tAnonymousUID: Name: Name 'AnonymousUID' cannot be used in type CodeFirstDatabaseSchema.AnonymousUID'. Member names cannot be the same as their enclosing type. ``` There is obviously some additional mapping build-up going on in `CodeFirstDatabaseSchema`, and this procedure is not able to avoid the class/member name clash. - Why does this error occur? After all, the reverse engineering procedure managed to circumvent the naming issue. - Without modifying the schema of the already established database, is there some way I can avoid this exception from being thrown? I am using Entity Framework 6.0 (pre-release) from Nuget in a .NET Framework 4 project.

Original source