Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop EF trying to update a computed column for SQL Server?

I have this object map for Entity Framework:

public WordDefinitionMap(string schema)
{
    ToTable(schema + ".WordDefinition");
    HasKey(x => x.WordDefinitionId);

    Property(x => x.WordDefinitionId).HasColumnName(@"WordDefinitionId").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
    Property(x => x.WordFormId).HasColumnName(@"WordFormId").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(20);
    Property(x => x.Ascii).HasColumnName(@"Ascii").IsOptional().HasColumnType("int").HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed);

    // Foreign keys
    HasRequired(a => a.WordForm).WithMany(b => b.WordDefinitions).HasForeignKey(c => c.WordFormId); // FK_WordDefinitionWordForm
}

public class WordDefinition
{
    public int WordDefinitionId { get; set; } // WordDefinitionId (Primary key)
    public string WordFormId { get; set; } // WordFormId (length: 20)
    public int? Ascii { get; set; } // Ascii

    // Foreign keys
    public virtual WordForm WordForm { get; set; } // FK_WordDefinitionWordForm
}

When I use Entity Framework to try to update this object I am getting an exception saying:

The column "Ascii" cannot be modified because it is either a computed column or is the result of a UNION operator.

I thought I was already instructing EF to ignore this property but it would seem it is still trying to update it even though it is null. Is there some way I can change the mapping so EF does not set this property?

like image 232
Samantha J T Star Avatar asked May 17 '16 17:05

Samantha J T Star


1 Answers

The exception message suggests that your fluent configuration is completely ignored by the framework because there is nothing wrong with you code.

Entity Framework then maps your properties using the standard convention, without knowing that Ascii property is a computed one.

To resolve the issue check that an instance of your WordDefinitionMap class is created and added to the modelBuilder:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new WordDefinitionMap("mySchema"));
    //other mappings
}

As an aside: I would suggest you to make your computed property not writeable by turning its setter private:

public int? Ascii { get; private set; } // Ascii

This will avoid mistakenly setting this property while EF will continue to populate it from the database without problems.

like image 113
Federico Dipuma Avatar answered Oct 23 '22 10:10

Federico Dipuma