How to update DataContext based on changes in the database structure?

前端 未结 3 510
天涯浪人
天涯浪人 2021-01-19 00:25

I\'m working in Visual Studio 2010 using linq-to-sql\'s DataContext which has several maps to tables in the database. Now when I change something to the structu

3条回答
  •  無奈伤痛
    2021-01-19 00:47

    In EF Core, you may find a certain "scaffolding" command helpful.

    Scaffolding can regenerate your DbContext as well as your Models. And in my experience, it won't override any custom partial classes you made to extend the DbContext, so those continue to work.

    You may need to install certain tools by adding them to your project.json (old)/ csproj (new)

    dotnet cli

    dotnet ef dbcontext scaffold --help`
    
    Usage: dotnet ef dbcontext scaffold [arguments] [options]
    Arguments:
        The connection string to the database.
          The provider to use. (E.g.  Microsoft.EntityFrameworkCore.SqlServer)
    

    This command (run from the project's root directory, assuming you keep your Models in a folder called "Models"); 1) updates my Models and 2) my DbContext. If you only wanted updates to your DbContext, I use source-control (git) to discard changes to the Models; keep changes to the DbContext.

    dotnet ef dbcontext scaffold "{connection}" Microsoft.EntityFrameworkCore.SqlServer \
    -f --output-dir=Models
    

    Powershell

    More info here, an abbreviated command:

    SYNTAX
        Scaffold-DbContext [-Connection]  [-Provider]  [-OutputDir ] [-Context ] [-Schemas ] [-Tables ] [-DataAnnotations] [-Force] [-Environment ] [-Project ] [-StartupProject ]
        []
    
    PARAMETERS
        -Connection 
            The connection string to the database.
    
        -Provider 
            The provider to use. (E.g. Microsoft.EntityFrameworkCore.SqlServer)
    
        -OutputDir 
            The directory to put files in. Paths are relaive to the project directory.
    
        -Context 
            The name of the DbContext to generate.
    
        ....
    
        -Force []
            Overwrite existing files.
    

提交回复
热议问题