的一部分,我有以下的EF代碼第一個實體及其相應的配置:使用自動生成的唯一標識符不屬於主鍵
public class Category
{
public virtual long Id { get; set; }
public Guid Guid { get; set; }
public string Name { get; set; }
}
public class CategoryConfiguration:
EntityTypeConfiguration<Category>
{
public CategoryConfiguration()
{
this.HasKey(entity => entity.Id);
this.Property(entity => entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(entity => entity.Guid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
設置DatabaseGeneratedOption.Identity
選項場上Guid
似乎有沒有效果,並且SQL Server中的相應表格禁用了IDENTITY
選項。
有沒有辦法在EF中自動生成一個GUID/UNIQUEIDENTIFIER列,但同時不是主鍵的一部分?
'IDENTITY'只適用於數字數據類型('int','逗號後有0位數的小數')。它**不能**被應用於'uniqueidentifier' –
可能的重複[實體框架代碼首先使用Guid作爲與另一個標識列的標識](http://stackoverflow.com/questions/12012736/entity-framework-code-first -using-guid-as-identity-with-another-identity-column) – Colin
難道你不能在實體的構造函數中做'Guid.NewGuid()'嗎?當你創建一個全新的,它將把guid設置爲新的東西。當你加載一個現有的實體時,它會將該值設置爲數據庫中的任何值。 – Dismissile