產生的值Generated Values

值,產生的模式Value Generation Patterns

有三種可用於屬性的值產生模式:There are three value generation patterns that can be used for properties:

  • 沒有值產生No value generation
  • 新增產生的值Value generated on add
  • 產生的值上新增或更新Value generated on add or update

沒有值產生No value generation

沒有值產生表示您將會永遠提供有效的值儲存到資料庫。No value generation means that you will always supply a valid value to be saved to the database. 有效的值必須指派給新的實體,新增至內容之前。This valid value must be assigned to new entities before they are added to the context.

新增產生的值Value generated on add

在產生的值新增表示值產生新的實體。Value generated on add means that a value is generated for new entities.

根據所使用的資料庫提供者,值可能會產生 EF 或在資料庫中的用戶端。Depending on the database provider being used, values may be generated client side by EF or in the database. 如果由資料庫所產生的值,然後 EF 時可能會指派暫時的值您將實體加入至內容。If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. 期間的資料庫產生值接著會取代此暫存值SaveChanges()This temporary value will then be replaced by the database generated value during SaveChanges().

如果您將實體新增至內容,其值指派給屬性時,EF 會嘗試將該值,而不是產生新的。If you add an entity to the context that has a value assigned to the property, then EF will attempt to insert that value rather than generating a new one. 屬性會被視為具有值,如果它不會指派 CLR 預設值指派 (null for string0intGuid.EmptyGuid等。)。A property is considered to have a value assigned if it is not assigned the CLR default value (null for string, 0 for int, Guid.Empty for Guid, etc.). 如需詳細資訊,請參閱 < 產生屬性的明確值For more information, see Explicit values for generated properties.

警告

值為已加入之實體的產生方式將取決於所使用的資料庫提供者。How the value is generated for added entities will depend on the database provider being used. 資料庫提供者可能會自動設定值,產生的某些屬性類型,但有些則可能需要您手動設定 產生值的方式。Database providers may automatically setup value generation for some property types, but others may require you to manually setup how the value is generated.

例如,使用 SQL Server 時,值將會自動產生的GUID(使用 SQL Server 的循序 GUID 演算法) 的屬性。For example, when using SQL Server, values will be automatically generated for GUID properties (using the SQL Server sequential GUID algorithm). 不過,如果您指定DateTime產生屬性上新增,則您必須設定要產生之值的方式。However, if you specify that a DateTime property is generated on add, then you must setup a way for the values to be generated. 若要這樣做,一個方法是設定預設值是GETDATE(),請參閱 < 預設值One way to do this, is to configure a default value of GETDATE(), see Default Values.

產生的值上新增或更新Value generated on add or update

產生的值上新增或更新可讓您表示每次儲存記錄時 (insert 或 update),就會產生新的值。Value generated on add or update means that a new value is generated every time the record is saved (insert or update).

例如value generated on add,如果您的實體,而不是所產生的值,將會插入值的新加入的執行個體上指定屬性的值。Like value generated on add, if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. 它也可更新時,設定明確的值。It is also possible to set an explicit value when updating. 如需詳細資訊,請參閱 < 產生屬性的明確值For more information, see Explicit values for generated properties.

警告

如何新增和更新實體,產生的值將取決於所使用的資料庫提供者。How the value is generated for added and updated entities will depend on the database provider being used. 資料庫提供者可能會自動安裝程式針對某些屬性類型,值產生,而有些則會需要您手動設定 產生值的方式。Database providers may automatically setup value generation for some property types, while others will require you to manually setup how the value is generated.

例如,當使用 SQL Serverbyte[]屬性設定為產生上新增或更新並標示為並行語彙基元,會使用設定rowversion資料類型-如此一來,值將會在資料庫中。For example, when using SQL Server, byte[] properties that are set as generated on add or update and marked as concurrency tokens, will be setup with the rowversion data type - so that values will be generated in the database. 不過,如果您指定DateTime產生屬性上新增或更新,則您必須設定要產生之值的方式。However, if you specify that a DateTime property is generated on add or update, then you must setup a way for the values to be generated. 若要這樣做,一個方法是設定預設值是GETDATE()(請參閱 < 預設值) 來產生新的資料列的值。One way to do this, is to configure a default value of GETDATE() (see Default Values) to generate values for new rows. 您接著可以使用的資料庫觸發程序來產生期間更新 (例如,下列的範例觸發程序) 的值。You could then use a database trigger to generate values during updates (such as the following example trigger).

CREATE TRIGGER [dbo].[Blogs_UPDATE] ON [dbo].[Blogs]
    AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;
                  
    IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
    
    DECLARE @Id INT
        
    SELECT @Id = INSERTED.BlogId
    FROM INSERTED
          
    UPDATE dbo.Blogs
    SET LastUpdated = GETDATE()
    WHERE BlogId = @Id
END

慣例Conventions

依照慣例,非複合主索引鍵,型別 short、 int、 long、 或是 Guid 將會有值上產生新增的設定。By convention, non-composite primary keys of type short, int, long, or Guid will be setup to have values generated on add. 所有其他屬性不會設定任何值產生。All other properties will be setup with no value generation.

資料註釋Data Annotations

沒有值產生 (資料註解)No value generation (Data Annotations)

public class Blog
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int BlogId { get; set; }
    public string Url { get; set; }
}

在產生的值加入 (資料註解)Value generated on add (Data Annotations)

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime Inserted { get; set; }
}

警告

這只是可讓 EF 知道產生新增實體的值,也無法保證 EF 將安裝程式的實際機制來產生值。This just lets EF know that values are generated for added entities, it does not guarantee that EF will setup the actual mechanism to generate values. 請參閱上產生的值加入一節以取得更多詳細資料。See Value generated on add section for more details.

在產生的值新增或更新 (資料註解)Value generated on add or update (Data Annotations)

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime LastUpdated { get; set; }
}

警告

這只是可讓 EF 知道產生新增或更新實體的值,也無法保證 EF 將安裝程式的實際機制來產生值。This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values. 請參閱上產生的值新增或更新一節以取得更多詳細資料。See Value generated on add or update section for more details.

Fluent APIFluent API

若要變更為指定屬性的值產生模式,您可以使用 Fluent API。You can use the Fluent API to change the value generation pattern for a given property.

沒有值產生 (Fluent API)No value generation (Fluent API)

modelBuilder.Entity<Blog>()
    .Property(b => b.BlogId)
    .ValueGeneratedNever();

在產生的值加入 (Fluent API)Value generated on add (Fluent API)

modelBuilder.Entity<Blog>()
    .Property(b => b.Inserted)
    .ValueGeneratedOnAdd();

警告

ValueGeneratedOnAdd() 只可讓 EF 知道產生新增實體的值,也無法保證 EF 將安裝程式的實際機制來產生值。ValueGeneratedOnAdd() just lets EF know that values are generated for added entities, it does not guarantee that EF will setup the actual mechanism to generate values. 請參閱上產生的值加入一節以取得更多詳細資料。See Value generated on add section for more details.

在產生的值新增或更新 (Fluent API)Value generated on add or update (Fluent API)

modelBuilder.Entity<Blog>()
    .Property(b => b.LastUpdated)
    .ValueGeneratedOnAddOrUpdate();

警告

這只是可讓 EF 知道產生新增或更新實體的值,也無法保證 EF 將安裝程式的實際機制來產生值。This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values. 請參閱上產生的值新增或更新一節以取得更多詳細資料。See Value generated on add or update section for more details.