从 .NET Framework 版本 4 开始,Entity Framework 支持数据定义语言(DDL)。 这样,可以根据连接字符串和存储 (SSDL) 模型的元数据创建或删除数据库实例。
以下方法在 ObjectContext 上使用连接字符串和 SSDL 内容来完成以下操作:创建或删除数据库、检查数据库是否存在,以及查看生成的 DDL 脚本。
注释
执行 DDL 命令假定有足够的权限。
前面列出的方法将大部分工作委托给基础 ADO.NET 数据提供程序。 提供程序负责确保用于生成数据库对象的命名约定与用于查询和更新的约定一致。
以下示例演示如何基于现有模型生成数据库。 它还将新的实体对象添加到对象上下文,然后将其保存到数据库。
过程
基于现有模型定义数据库
创建控制台申请。
将现有模型添加到应用程序。
- 添加名为
SchoolModel
的空模型。 若要创建空模型,请参阅 How to: Create a New .edmx File 主题。
SchoolModel.edmx 文件将添加到项目中。
从 学校模型 主题复制学校模型的概念、存储和映射内容。
打开 SchoolModel.edmx 文件,并将内容粘贴到标记中
edmx:Runtime
。
- 添加名为
将以下代码添加到主函数。 该代码将连接字符串初始化到数据库服务器,查看 DDL 脚本,创建数据库,向上下文添加新实体,并将更改保存到数据库。
// Initialize the connection string. String connectionString = "..."; using (SchoolEntities context = new SchoolEntities(connectionString)) { try { if (context.DatabaseExists()) { // Make sure the database instance is closed. context.DeleteDatabase(); } // View the database creation script. Console.WriteLine(context.CreateDatabaseScript()); // Create the new database instance based on the storage (SSDL) section // of the .edmx file. context.CreateDatabase(); // The following code adds a new objects to the context // and saves the changes to the database. Department dpt = new Department { Name = "Engineering", Budget = 350000.00M, StartDate = DateTime.Now }; context.Departments.AddObject(dpt); // An entity has a temporary key // until it is saved to the database. Console.WriteLine(dpt.EntityKey.IsTemporary); context.SaveChanges(); // The object was saved and the key // is not temporary any more. Console.WriteLine(dpt.EntityKey.IsTemporary); } catch (InvalidOperationException ex) { Console.WriteLine(ex.InnerException.Message); } catch (NotSupportedException ex) { Console.WriteLine(ex.InnerException.Message); } }
' Initialize the connection string. Dim connectionString As String = "metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;" & "provider connection string=""Data Source=.;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True""" Using context As New SchoolEntities(connectionString) Try If context.DatabaseExists() Then ' Make sure the database instance is closed. context.DeleteDatabase() End If ' View the database creation script. Console.WriteLine(context.CreateDatabaseScript()) ' Create the new database instance based on the storage (SSDL) section ' of the .edmx file. context.CreateDatabase() ' The following code adds a new objects to the context ' and saves the changes to the database. Dim dpt As New Department() context.Departments.AddObject(dpt) ' An entity has a temporary key ' until it is saved to the database. Console.WriteLine(dpt.EntityKey.IsTemporary) context.SaveChanges() ' The object was saved and the key ' is not temporary any more. Console.WriteLine(dpt.EntityKey.IsTemporary) Catch ex As InvalidOperationException Console.WriteLine(ex.InnerException.Message) Catch ex As NotSupportedException Console.WriteLine(ex.InnerException.Message) End Try End Using