使用数据定义语言

从 .NET Framework 第 4 版开始,实体框架支持数据定义语言 (DDL)。 这样,您将能够基于连接字符串和存储元数据 (SSDL) 模型创建或删除数据库实例。

ObjectContext 的以下方法使用连接字符串和 SSDL 内容来完成以下操作:创建或删除数据库,检查数据库是否存在,以及查看生成的 DDL 脚本:

备注

假定有足够的权限可执行 DDL 命令。

以上列出的方法将大部分工作都委托给基础 ADO.NET 数据提供程序。 该提供程序负责确保用于生成数据库对象的命名约定与用于查询和更新的约定保持一致。

下面的示例演示如何基于现有模型生成数据库。 它还将新的实体对象添加到对象上下文中,然后将该对象保存到数据库中。

过程

基于现有模型定义数据库

  1. 创建控制台应用程序。

  2. 向应用程序中添加现有模型。

    1. 添加名为 SchoolModel 的空模型。 若要创建空模型,请参阅如何:创建新的 .edmx 文件主题。

    将 SchoolModel.edmx 文件添加到您的项目中。

    1. 复制 School 模型主题中 School 模型的概念、存储和映射内容。

    2. 打开 SchoolModel.edmx 文件并将内容粘贴在 edmx:Runtime 标记中。

  3. 将以下代码添加到主函数中。 此类代码将连接字符串初始化为数据库服务器,查看 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