Specifies how the database generates values for the property. There are three possible values:
None
specifies that the values are not generated by the database.Identity
specifies that the column is an identity column, which is typically used for integer primary keys.Computed
specifies that the database generates the value for the column.If the value is anything other than None
, Entity Framework will not commit changes made to the property back to the database.
By default (based on the StoreGeneratedIdentityKeyConvention
) an integer key property will be treated as an identity column. To override this convention and force it to be treated as a non-identity column you can use the DatabaseGenerated
attribute with a value of None
.
using System.ComponentModel.DataAnnotations.Schema;
public class Foo
{
[Key]
public int Id { get; set; } // identity (auto-increment) column
}
public class Bar
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; } // non-identity column
}
The following SQL creates a table with a computed column:
CREATE TABLE [Person] (
Name varchar(100) PRIMARY KEY,
DateOfBirth Date NOT NULL,
Age AS DATEDIFF(year, DateOfBirth, GETDATE())
)
GO
To create an entity for representing the records in the above table, you would need to use the DatabaseGenerated
attribute with a value of Computed
.
[Table("Person")]
public class Person
{
[Key, StringLength(100)]
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Age { get; set; }
}