user5032790
user5032790

Reputation:

Why I'm gettin Cannot insert the value NULL into computed column?

I'm using EF-Code First and this is my model with Data Annotation:

public int Count { get; set; }
public int Fee { get; set; }

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Total { get; set; }

Or like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

public int Total
{
    get { return Fee * Count; }
    private set{}
}

When I want to create a new record I'm getting the following error:

Cannot insert the value NULL into column 'Total'; column does not allow nulls. INSERT fails. The statement has been terminated.

As you can see I'm getting the correct computed value in the Create Action Method with model binder:

enter image description here

By removing the DatabaseGenerated(DatabaseGeneratedOption.Computed) and set the computed value from my code it works fine and I see the updated total in the database. But my question is if I can do this without DatabaseGenerated(DatabaseGeneratedOption.Computed) so what's the DatabaseGenerated(DatabaseGeneratedOption.Computed) usage?

This works:

public int Total
{
    get { return Fee * Count; }
    private set{}
}

Upvotes: 2

Views: 1533

Answers (2)

Alex
Alex

Reputation: 1461

As mentioned here and here you can't update a calculated column because it's value is retreived from database and never sent back.

So the solution would be to create another not mapped calculated property in your model which will be used in your code and keep your Total property mapped to the database:

public int Count { get; set; }
public int Fee { get; set; }
public int Total { get; set; }

[NotMapped]
public int CalculatedTotal
{
    get { return Count*Fee; }
}

Upvotes: 1

Elmer Dantas
Elmer Dantas

Reputation: 4869

Try to declare public int? Total to accept null.

Upvotes: 0

Related Questions