I don't want EF to ignore the column on the class when retrieving records from the database as I need to be able to compare the computed column, but I don't want EF to try to insert values into this column as that will throw a SQL Exception because computed columns cannot be modified.
Asked
Active
Viewed 568 times
3 Answers
4
You can use DatabaseGenerated attribute:
using System.ComponentModel.DataAnnotations.Schema;
....
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int ComputedColumn { get; set; }

Miamy
- 2,162
- 3
- 15
- 32
1
DatabaseGeneratedOption.Identity
This specifies that the value of the property will be generated by the database on the INSERT statement. This Identity property cannot be updated.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
DatabaseGeneratedOption.Compute Specifies that the value of the property will be generated by the underlying database on insert and then, on each subsequent update. Useful for LastAccessTime and things like that

Arys
- 477
- 3
- 12
1
If you are using the fluent API in OnModelCreating
then you can use
entity.Property(e => e.ComputedColumn)
.ValueGeneratedOnAddOrUpdate();
There is also a ValueGeneratedOnAdd
and ValueGeneratedOnUpdate
if the value is only computed on insert or update respectively.

Richard Blewett
- 6,089
- 1
- 18
- 23