Trabalhando com a linguagem de definição de dadosWorking with Data Definition Language

A partir do .NET Framework versão 4, o Entity Framework dá suporte a DDL (linguagem de definição de dados).Starting with the .NET Framework version 4, the Entity Framework supports data definition language (DDL). Isso permite que você crie ou exclua uma instância do banco de dados com base na cadeia de conexão e nos metadados do modelo de armazenamento (SSDL).This allows you to create or delete a database instance based on the connection string and the metadata of the storage (SSDL) model.

Os métodos a seguir no ObjectContext usam a cadeia de conexão e o conteúdo SSDL para criar ou excluir o banco de dados, verificar se o banco de dados existe e exibir o script DDL gerado:The following methods on the ObjectContext use the connection string and the SSDL content to accomplish the following: create or delete the database, check whether the database exists, and view the generated DDL script:

Observação

A execução de comandos DDL pressupõe permissões suficientes.Executing the DDL commands assumes sufficient permissions.

Os métodos listados anteriormente delegam a maioria do trabalho para o provedor de dados ADO.NET subjacente.The methods previously listed delegate most of the work to the underlying ADO.NET data provider. É responsabilidade do provedor garantir que a convenção de nomenclatura usada para gerar objetos de banco de dados seja consistente com as convenções usadas nas consultas e atualizações.It is the provider’s responsibility to ensure that the naming convention used to generate database objects is consistent with conventions used for querying and updates.

O exemplo a seguir mostra como gerar o banco de dados com base no modelo existente.The following example shows you how to generate the database based on the existing model. Ele também adiciona um novo objeto de entidade ao contexto de objeto e os salva no banco de dados.It also adds a new entity object to the object context and then saves it to the database.

ProcedimentosProcedures

Para definir um banco de dados com base no modelo existenteTo define a database based on the existing model

  1. Crie um aplicativo de console.Create a console application.

  2. Adicione um modelo existente ao seu aplicativo.Add an existing model to your application.

    1. Adicione um modelo vazio chamado SchoolModel .Add an empty model named SchoolModel. Para criar um modelo vazio, consulte o tópico como: criar um novo arquivo. edmx .To create an empty model, see the How to: Create a New .edmx File topic.

    O arquivo SchoolModel.edmx é adicionado ao projeto.The SchoolModel.edmx file is added to your project.

    1. Copie o conteúdo conceitual, de armazenamento e de mapeamento para o modelo escolar do tópico de estudante Model .Copy the conceptual, storage, and mapping content for the School model from the School Model topic.

    2. Abra o arquivo SchoolModel.edmx e cole o conteúdo nas marcas edmx:Runtime.Open the SchoolModel.edmx file and paste the content within the edmx:Runtime tags.

  3. Adicione o seguinte código à função principal.Add the following code to your main function. O código inicializa a cadeia de conexão ao servidor de banco de dados, exibe o script DDL, cria o banco de dados, adiciona uma nova entidade ao contexto e salva as alterações no banco de dados.The code initializes the connection string to your database server, views the DDL script, creates the database, adds a new entity to the context, and saves the changes to the database.

    // Initialize the connection string.
    String connectionString = "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 (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