Entity Framework 6 Code First series: SQLite. CodeFirst automatically generates the database, entityframework6
In Code First mode, SQLite is always used to Prevent Automatic database generation. SQL Server Compact is used to convert the data to SQLite (SQL Server Compact/SQLite Toolbox plug-in) it is basically out of my consideration. It is a problem to directly use SQL Server Compact performance. In theory, we can implement the Code Frist support of SQLite by ourselves, but in fact I am just waiting for its appearance. We have been expecting SQLite. CodeFirst for more than a year.
1. First define entities: Customer, Role, Category, and Post.
Public class BaseEntity {public int Id {get; set ;}} public class Customer: BaseEntity {public Customer () {this. roles = new List <Role> ();} public string UserName {get; set;} public virtual ICollection <Role> Roles {get; set ;}} public class Role: baseEntity {public Role () {this. customers = new List <Customer> ();} public virtual ICollection <Customer> Customers {get; set;} public strin G RoleName {get; set ;}} public class Category: BaseEntity {public Category () {this. children = new List <Category> (); this. posts = new List <Post> ();} public int? ParentId {get; set;} public virtual Category Parent {get; set;} public virtual ICollection <Category> Children {get; set;} public virtual ICollection <Post> Posts {get; set ;}} public class Post: BaseEntity {public virtual Category {get; set ;}}View Code
2. Define object ing: CustomerMap, RoleMap, CategoryMap, and PostMap are used as the configuration of Relational Tables and indexes.
Public class CustomerMap: EntityTypeConfiguration <Customer> {public CustomerMap () {this. property (o => o. userName ). hasColumnAnnotation ("Index", new IndexAnnotation (new IndexAttribute () {IsUnique = true}) ;}} public class RolerMap: EntityTypeConfiguration <Role> {public RolerMap () {this. haswon (o => o. MERs mers ). withMany (o => o. roles) ;}} public class CategoryMap: EntityTypeConfiguration <Category> {public CategoryMap () {this. hasOptional (o => o. parent ). withMany (o => o. children ). hasForeignKey (o => o. parentId) ;}} public class PostMap: EntityTypeConfiguration <Post> {public PostMap () {this. hasOptional (o => o. category ). withMany (o => o. posts );}}View Code
3. Define initialization data: currently, SQLite. CodeFist only supports the DropCreateDatabaseAlways and CreateDatabaseIfNotExists methods, which is just a few days from issues.
Public class MyDbInitializer: extends <SqliteDbContext> {public MyDbInitializer (string connectionString, DbModelBuilder modelBuilder): base (connectionString, modelBuilder) {} protected override void Seed (SqliteDbContext context) {context. set <Customer> (). add (new Customer {UserName = "user" + DateTime. now. ticks. toString (), Roles = new List <Role >{new Role {RoleName = "user" }}}); context. set <Post> (). add (new Post {Category = new Category ()}); base. seed (context );}}View Code
4. Define DbContext: PluralizingTableNameConvention must be configured here, otherwise it will not work properly.
Public class SqliteDbContext: DbContext {public SqliteDbContext (): base ("DefaultConnection") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder. conventions. remove <PluralizingTableNameConvention> (); modelBuilder. events. addFromAssembly (typeof (SqliteDbContext ). assembly); # if DEBUG Database. setInitializer (new MyDbInitializer (Database. connection. connectionString, modelBuilder); # endif }}View Code
5. Configure Web. config: the default configuration file. You can directly copy the configuration file for testing in the project.
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- For more information about how to configure ASP. NET applications, visit http://go.microsoft.com/fwlink/?LinkId=301880 --> <Configuration> <configSections> <! -- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <Section name = "entityFramework" type = "System. data. entity. internal. configFile. entityFrameworkSection, EntityFramework, Version = 6.0.0.0, Culture = neutral, PublicKeyToken = token "requirePermission =" false "/> </configSections> <appSettings> <add key =" webpages: version "value =" 3.0.0.0 "/> <add key =" webpages: enabled "value =" false "/> <add key =" ClientValidationEnabled "value =" true "/> <add key =" UnobtrusiveJavaScriptEnabled "value =" true "/> </appSettings> <connectionStrings> <add name = "DefaultConnection" connectionString = "data source = | DataDirectory | \ db. sqlite "providerName =" System. data. SQLite "/> </connectionStrings> <system. web> <compilation debug = "true" targetFramework = "4.5"/>
6. configure Global. asax.
Public class MvcApplication: System. web. httpApplication {protected void Application_Start () {using (var db = new SqliteDbContext () {} AreaRegistration. registerAllAreas (); RouteConfig. registerRoutes (RouteTable. routes );}}View Code
View the generated database: The table ing, link ing, and index are created correctly.
Call:
Download Demo