2
我有我使用的是Azure的移動服務下面的代碼,第一實體框架代碼:如何在EF code-first和Azure中創建默認約束?
public class BookContext : DbContext
{
private const string connectionStringName = "Name=MS_TableConnectionString";
public BookContext() : base(connectionStringName) { }
// The collections queried directly.
public DbSet<Book> Books{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Standard code to add the "service" columns such as CreatedAt, UpdatedAt, and Deleted.
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
// Add a default value 0 on the Deleted column. The following code does not work.
modelBuilder.Entity<Book>()
.Property(p => p.Deleted)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
}
}
如上所述,該代碼應該被刪除的列上添加一個默認約束,但它確實不做任何事情。我希望實現與EF代碼優先級相同的以下SQL語句:
ALTER TABLE dbo.Books ADD CONSTRAINT DF_BooksDeleted DEFAULT 0 FOR Deleted
顯然,我必須做錯了什麼。任何人都可以將我指向正確的方向嗎?
由於布魯斯。你的代碼運行良好。實際上,我只需要添加EntityTableSqlGenerator並按原樣離開OnModelCreating。無論如何,已創建「已刪除」列的默認約束。爲什麼我需要爲OnModelCreating中的已刪除列設置默認值? – ata6502
我以爲'Deleted'列沒有默認約束,謝謝提醒我。要爲自定義列設置默認值,可以參考其餘部分。 –
讓我澄清一下:MyEntityTableSqlGenerator的用途是設置Default約束的值。 OnModelCreating的目的是創建Default約束。這是對的嗎?如果是這樣,我可能已經運行創建了默認約束的OnModelCreating。 – ata6502