2014-02-25 58 views
1

我正在尋找一種以編程方式爲基於DbContext的給定數據庫編程生成實體框架模型數據庫的方法。如何以編程方式生成基於DbContext的實體框架模型DbFirst

現在,我一直在試驗類System.Data.Entity.Design.EntityCodeGenerator,但似乎只基於ObjectContext生成它們。

http://msdn.microsoft.com/en-us/library/system.data.entity.design.entitycodegenerator(v=vs.110).aspx

在這裏,我找到了如何使用它的信息: http://blogs.msdn.com/b/adonet/archive/2008/06/20/edm-tools-options-part-1-of-4.aspx

但仍然只生成ObjectContext的基於模型。

更新:我需要從Visual Studio擴展內部執行此操作(因此它將Visual Studio作爲沙箱)。

回答

1

好吧,我終於找到了一種方法,而不是使用System.Data.Entity.Design.EntityCodeGenerator爲模型後端(例如Model.Designer.cs)生成代碼,現在我只需將.edmx添加到Visual Studio項目,設置一些屬性,和Visual Studio完成所有的操作:

private void AddToProject(string edmxPath) 
    { 
     string edmxCodePath; 
     ProjectItem pi = _vsProj.Project.ProjectItems.AddFromFile(edmxPath); 
     // this little magic replaces having to use System.Data.Entity.Design.EntityCodeGenerator 
     pi.Properties.Item("ItemType").Value = "EntityDeploy"; 
     pi.Properties.Item("CustomTool").Value = "EntityModelCodeGenerator"; 
     if(efVersion == BaseWizard<BaseWizardForm, BaseCodeGeneratorStrategy>.ENTITY_FRAMEWORK_VERSION_6) 
     { 
     // For EF6 we use DbContext instead of ObjectContext based context. 
     _vsProj.DTE.SuppressUI = true; 
     EnvDTE80.Solution2 sol = (EnvDTE80.Solution2)_vsProj.DTE.Solution; 
     string itemPath = ""; 
     if(this.Language == LanguageGenerator.CSharp) 
     { 
      itemPath = sol.GetProjectItemTemplate("DbCtxCSEF6", "CSharp"); 
     } else { 
      itemPath = sol.GetProjectItemTemplate("DbCtxVBEF6", "VisualBasic"); 
     } 
     pi.ProjectItems.AddFromTemplate(itemPath, this._modelName); 
     // update $edmxInputFile$ 
     string path = Path.GetDirectoryName(edmxPath); 
     string templateName = Path.Combine(path, _modelName + ".tt"); 
     string contents = File.ReadAllText(templateName); 
     File.WriteAllText(templateName, contents.Replace("$edmxInputFile$", _modelName + ".edmx")); 
     templateName = Path.Combine(path, _modelName + ".Context.tt"); 
     contents = File.ReadAllText(templateName); 
     File.WriteAllText(templateName, contents.Replace("$edmxInputFile$", _modelName + ".edmx")); 
     } 
    } 

說明:該方法接收所產生的.edmx文件路徑,如果EF版本是6,模板「DbCtxCSEF6」是instantied(它始終與VS2013一起安裝),然後就是用edmx文件名替換$ edmxInputFile $; Visual Studio會自動添加.tt模板並生成後端代碼。

有關上下文中的更多詳細信息,請參閱MySql中用於Visual Studio 1.2.1或更高版本的MySql.Data.VisualStudio.Wizards.EntityFrameworkGenerator類的代碼。

安裝程序及源代碼(其開源)可在:

http://dev.mysql.com/downloads/windows/visualstudio/

相關問題