我向MVC 5 Web API項目添加了一個新實體,但無法使用它與我現有的SQL一起工作數據庫。我現有的代碼使用工作單元工廠和存儲庫模式從數據庫讀取和寫入,所以我知道代碼工作。沒有edmx文件,所以我相信代碼最初是使用代碼編寫的。這是我迄今採取的步驟。實體框架6.1.1無法獲得新實體與Unity Work of Factory和Repository模式兼容
步驟1)增加了新的實體,以我的實體文件夾 步驟2)更新的DbContext文件 步驟3)更新UnitOfWork.cs文件 步驟4)手動創建的腳本使用步驟 5個新的SQL表)的添加以下代碼到我的Web API服務
using (var uow = _unitOfWorkFactory.Create())
{
//Code to create newentity object
uow.newEntityRepository.Insert(newentity);
await uow.SaveChangesAsync();
}
我沒有收到錯誤。插入操作不會將記錄添加到數據庫。
我已經使用EntityTypeConfiguration創建了一個實體表映射,我使用OnModelCreating Override調用它。
EntityTypeConfiguration
public class NewEntityMap : EntityTypeConfiguration<NewEntity>
{
public NewEntityMap() : base()
{
// Primary Key
this.HasKey(t => t.Id);
// Table & Column Mappings
this.ToTable("NewEntity", "dbo");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Created).HasColumnName("Created");
this.Property(t => t.OfferId).HasColumnName("OfferId");
this.Property(t => t.MerchantId).HasColumnName("MerchantId");
this.Property(t => t.ConsumerId).HasColumnName("ConsumerId");
this.Property(t => t.SMSMessage).HasColumnName("SMSMessage");
this.Property(t => t.SendSMS).HasColumnName("SendSMS");
this.Property(t => t.EmailMessage).HasColumnName("EmailMessage");
this.Property(t => t.SendEmail).HasColumnName("SendEmail");
this.Property(t => t.Source).HasColumnName("Source");
this.Property(t => t.FromSMSNumber).HasColumnName("FromSMSNumber");
}
}
OnModelCreating
modelBuilder.Configurations.Add(new newEntityMap());
我仍然不能得到記錄在表更新。
任何想法?提前致謝!
它看起來像基於這個堆棧溢出的問題,實體可以手動映射,而無需進行數據庫遷移。 http://stackoverflow.com/questions/20243796/code-first-mapping-entities-to-existing-database-tables –
這篇博客文章甚至沒有提到數據庫遷移的必要性。 http://cpratt.co/entity-framework-code-first-with-existing-database/ –