Search code examples
c#entity-frameworkapifluent

Entity Framework Fluent API: An object of type 'IndexAttribute' cannot be serialized by the IndexAnnotationSerializer.


I'm using EF 6.1.3 and got this error.

"An object of type 'IndexAttribute' cannot be serialized by the IndexAnnotationSerializer. Only 'IndexAnnotation' objects can be serialized."

Here is one of the config files

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
using MasterDetails.Models;

namespace MasterDetails.DataLayer
{
    public class InventoryItemConfiguration :     EntityTypeConfiguration<InventoryItem>
{
    public InventoryItemConfiguration()
    {
        Property(ii => ii.InventoryItemCode)
            .HasMaxLength(15)
            .IsRequired()
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("AK_InventoryItem_InventoryItemCode") { IsUnique = true }));

        Property(ii => ii.InventoryItemName)
            .HasMaxLength(80)
            .IsRequired()
            .HasColumnAnnotation("Index", new IndexAttribute("AK_InventoryItem_InventoryItemName") { IsUnique = true });

        Property(ii => ii.UnitPrice)
            .HasPrecision(18, 2);
    }
}
}

Solution

  • The exception is caused by the following line

    .HasColumnAnnotation("Index", new IndexAttribute("AK_InventoryItem_InventoryItemName") { IsUnique = true });
    

    You need to wrap IndexAttribute inside the IndexAnnotation (as you already correctly did for the other column InventoryItemCode):

    .HasColumnAnnotation("Index", new IndexAnnotation(
        new IndexAttribute("AK_InventoryItem_InventoryItemName") { IsUnique = true }));