Entity Framework 7: An anonymous type cannot have multiple properties with the same name

entity-framework entity-framework-core

Question

In the past I've had problems (1, 2, 3) with Entity Framework when swapping between development machines, so I wanted to get something simple up-and-running with Entity Framework 7 RC1 Update 1 to see if things were easier.

I copied an Azure database locally and then used the DNX command

dnx ef dbcontext scaffold "Server=MYDESK;Database=mydatabase;Trusted_Connection=True;" EntityFramework.MicrosoftSqlServer --outputDir Models

This created the data model classes and the context class. I checked that in and have now swapped to another machine and checked out the code. On the new machine it fails to build throwing an error in the code generated by Entity Framework 7:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Items>(entity =>
    {
        entity.ToTable("Items", "myapi");

        entity.HasIndex(e => new { e.CreatedAt, e.CreatedAt, e.CreatedAt, e.CreatedAt }).HasName("IX_CreatedAt");

The build error, on that last line, is "An anonymous type cannot have multiple properties with the same name". Why is Entity Framework 7 generating code that will not build and how do I fix it?

Accepted Answer

It looks like this is a known bug: SQL Server scaffolding generates invalid anonymous types for indexes (rc1-final) #3847, caused by "conflating indexes which had the same name but were on different tables". It is fixed in more recent commits to the milestone Entity Framework 7 RC2 (roadmap).


Popular Answer

The error is clear..you cannot have multiple properties with the same name... Change your last line to below:

    entity.HasIndex(e => new { 
                     CreatedAt = e.CreatedAt, 
                     Name2 = e.CreatedAt, 
                     Name3 = e.CreatedAt, 
                     Name4 = e.CreatedAt }).HasName("IX_CreatedAt");


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why