Auto Create Database Tables from Objects, Entity Framework

前端 未结 5 1268
陌清茗
陌清茗 2020-12-16 00:35

I am trying to do this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part4-cs but instead of using the compact edition

5条回答
  •  [愿得一人]
    2020-12-16 01:05

    You can use FenixRepo library(also available as nuget package) to create particular table, that is a part of you Context. First of all, you should call one time, at startup static Initialize method, where first argument is a factory method, which returns instance of your Context and the second one is an instance of Configuration class. It will prepare SQL scripts for all of your tables, registered at your Context. At case of ASP.NET MVC it is a good decision to paste this code into Global.asax:

    FenixRepositoryScriptExtractor.Initialize(() => new Context(), new Configuration());
    

    Then you can create table of desired type MyTable this simple way:

    var repo = new FenixRepositoryCreateTable();
    //or repo = new FenixRepository();
    
    repo.CreateTable();
    

    Also, if your table spread between several migrations and they have nothing stuff corresponded to other tables, you can specify these migrations(i.e. names of classes from Migrations folder) via FenixAttribute, and exactly they will be used as source of SQL scripts, which will be used for table creation:

    [Fenix(nameof(Initial), nameof(MyTableFirstMigration), nameof(MyTableSecondMigration))]
    public class MyTable
    {
        //some stuff
    }
    

    Without this attribute, library will use default scripts. It is always better to specify migrations, because otherwise it is not guaranteed that all indexes will be created and also into your migrations you can include some custom code, that will not be executed at case of default solution.

    Library is compatible and tested with EF 6.1.3 at case of MS SQL.

提交回复
热议问题