好的,我找到了一种方法,在这里记录它以防其他人遇到相同的问题:而不是使用 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”(VS2013始终安装),则只需替换$edmxInputFile$即可带有 edmx 文件名; Visual Studio 将自动添加 .tt 模板并生成后端代码。
有关上下文的更多详细信息,请参阅 MySql for Visual Studio 1.2.1 或更高版本中 MySql.Data.VisualStudio.Wizards.EntityFrameworkGenerator 类的代码。
安装程序和源代码(其开源)可在:
http://dev.mysql.com/downloads/windows/visualstudio/