Aracılığıyla paylaş


Veri Tanımlama Dili ile Çalışma

.NET Framework sürüm 4'den başlayarak, Entity Framework veri tanımı dilini (DDL) destekler. Bu, depolama (SSDL) modelinin bağlantı dizesi ve meta verilerine göre bir veritabanı örneği oluşturmanıza veya silmenize olanak tanır.

Aşağıdaki yöntemleri ObjectContext kullanarak bağlantı dizesi ve SSDL içeriğini kullanarak aşağıdakileri gerçekleştirebilirsiniz: veritabanını oluşturun veya silin, veritabanının var olup olmadığını denetleyin ve oluşturulan DDL betiğini görüntüleyin:

Not

DDL komutlarının yürütülmesi yeterli izinler olduğunu varsayar.

Daha önce listelenen yöntemler, çalışmanın çoğunu temel ADO.NET veri sağlayıcısına devreder. Veritabanı nesneleri oluşturmak için kullanılan adlandırma kuralının sorgulama ve güncelleştirmeler için kullanılan kurallarla tutarlı olduğundan emin olmak sağlayıcının sorumluluğundadır.

Aşağıdaki örnekte, veritabanının var olan modele göre nasıl oluşturulacağı gösterilmektedir. Ayrıca nesne bağlamı için yeni bir varlık nesnesi ekler ve sonra veritabanına kaydeder.

Yordamlar

Mevcut modeli temel alan bir veritabanı tanımlamak için

  1. Bir konsol uygulaması oluşturun.

  2. Uygulamanıza var olan bir modeli ekleyin.

    1. adlı SchoolModelboş bir model ekleyin. Boş bir model oluşturmak için Nasıl yapılır: Yeni .edmx Dosyası Oluşturma konusuna bakın.

    SchoolModel.edmx dosyası projenize eklenir.

    1. Okul Modeli konusundan School modeli için kavramsal, depolama ve eşleme içeriğini kopyalayın.

    2. SchoolModel.edmx dosyasını açın ve içeriği etiketlere yapıştırın edmx:Runtime .

  3. Aşağıdaki kodu ana işlevinize ekleyin. Kod veritabanı sunucunuza bağlantı dizesi başlatır, DDL betiğini görüntüler, veritabanını oluşturur, bağlama yeni bir varlık ekler ve değişiklikleri veritabanına kaydeder.

    // 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