天天看點

NopCommerce資料遷移之【添加新增實體的示例資料】

添加新增實體的示例資料

在Libraries\Nop.Services\Installation\CodeFirstInstallationService.cs檔案中添加服務成員變量:

private readonlyIRepository<Link>_linkRepository;

然後給CodeFirstInstallationService構造函數添加對應的參數IRepository<LinkModel>linkRepository,并給_linkRepository指派。

接着添加函數:

protected virtualvoid InstallLinks()

{

   List<Link> links =newList<Link>()

   {

       new Link {Name="Zaxx",Value="最愛肖霄——zaxx" }

   };

   _linkRepository.Insert(links);

}

最後在InstallData函數中添加對InstallLinks()函數的調用。

另外還要在Presentation\Nop.Web\App_Data\Install\create_sample_data.sql檔案中添加下面語句:

SETIDENTITY_INSERT [dbo].[Link] ON

INSERT[dbo].[Link] ([Id], [Name], [Value]) VALUES (1, N'Zaxx', N'最愛肖霄——zaxx')

SETIDENTITY_INSERT [dbo].[Link] OFF

GO

DependencyRegistrar的Register中會根據Web.config檔案中UseFastInstallationService(使用快速安裝服務)的配置值來判斷是用SqlFileInstallationService的InstallData執行create_sample_data.sql檔案向資料庫中插入示範資料,還是使用CodeFirstInstallationService的InstallData向資料庫中插入示範資料。Web.config檔案中UseFastInstallationService為預設是false,将CodeFirstInstallationService的InstallData向資料庫中插入示範資料(注意:若插入的中文資料是亂碼,則用記事本打開CodeFirstInstallationService.cs,把它的編碼改為UTF-8)。

注意:遷移時未向資料庫中插入示範資料,因為在之前的代碼中,未在Configuration.cs的Seed方法中給出示範資料。若有需要,可以自行給出。在資料庫中已有示範資料時,按之前所述的遷移步驟對資料庫進行更新時,已有示範資料是不會丢失的。

個人推廣:文章代寫與軟體開發

繼續閱讀