Search code examples
c#entity-framework-coreef-code-firstef-core-5.0

How can I resolve error 'No best type found for implicitly-typed array' while creating unique constraint on properties of different types?


QUESTION: Using EF Core (v5), how can I resolve the compiler error 'No best type found for implicitly-typed array' in a way that allow me to create a unique database constraint on multiple properties of different types?

I'm using code such as this:

modelBuilder.Entity<Entity>().HasAlternateKey(entity => new [] {entity.COL1, entity.COL2}).HasName("UniqueCOL1_COL2");

// example sourced from: https://learn.microsoft.com/en-us/answers/questions/187856/code-first-unique-constraint-on-multiple-columns.html#answer-190078

In my case, I'm seeing a compiler error No best type found for implicitly-typed array, because COL1 and COL2 are of different types (string and int in this case).

This SO post explains the cause of the error, but does not explain how I can resolve the issue highlighted by my question.

I tried using an array of objects but that didn't work:

new object[] {entity.COL1, entity.COL2}

Solution

  • I was able to resolve this issue using an anonymous object. For example:

    builder.HasAlternateKey(e => new { e.SomeInt, e.SomeString })