วันจันทร์ที่ 28 พฤศจิกายน พ.ศ. 2559

Guide to Create Entity Framework Code First from Stratch

1. Create a model (or a class!) that describe the data structure on your requirement.

Public Class Album
    Public Overridable Property AlbumId As Integer
    Public Overridable Property GenreId As Integer
    Public Overridable Property ArtistId As Integer
    Public Overridable Property Title As String
    Public Overridable Property Price As Decimal
    Public Overridable Property AlbumArtUrl As String
End Class

Don't worry about the annotation you can update it later. But it is a good practice to add it first.

2. Create a database context class that inherits DbContext.

Imports System.Data.Entity
 
Namespace Models
    
    Public Class MusicStoreDbContext
        Inherits DbContext
        Public Sub New()
            MyBase.New("MusicStoreDB")
        End Sub
    End Class
 
End Namespace


Note that: the parameter in the constructor is the connection name in the connection string of the Web.config.

<add name="MusicStoreDB" connectionString="..."
      providerName="System.Data.SqlClient" />

3. Add the DbSet property of the model to the context class.

Imports System.Data.Entity
 
Namespace Models
    
    Public Class MusicStoreDbContext
        Inherits DbContext
        Public Sub New()
            MyBase.New("MusicStoreDB")
        End Sub
    
        Public Property Albums As DbSet(Of Album)
    End Class End Namespace
That's it! Then you can start database migrations.

Enable-Migrations
Add-Migration
Update-Database

ไม่มีความคิดเห็น:

แสดงความคิดเห็น