http://www.cnblogs.com/easygame/p/4447457.html

在Code First模式下使用SQLite一直存在不能自动生成数据库的问题,使用SQL Server Compact再转换到SQLite的方式(SQL Server Compact/SQLite Toolbox插件)基本不在我的考虑范围内,直接使用SQL Server Compact性能又是问题。理论上我们可以自己去实现SQLite的Code Frist支持,但实际上我只是在等待它的出现。期待了一年多,SQLite.CodeFirst真的出现了。

1.首先定义实体:

Customer、Role、Category、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 string 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 Category { get; set; }
}

2.定义实体映射

CustomerMap、RoleMap、CategoryMap和PostMap作为关系表、索引的配置。

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.HasMany(o => o.Customers).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);
}
}

3.定义初始化数据:

目前SQLite.CodeFist只支持DropCreateDatabaseAlways和CreateDatabaseIfNotExists方式。

public class MyDbInitializer : SqliteDropCreateDatabaseAlways<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);
}
}

4.定义DbContext:

此处必须配置PluralizingTableNameConvention,否则无法正常使用。

public class SqliteDbContext : DbContext
{
public SqliteDbContext()
: base("DefaultConnection")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.AddFromAssembly(typeof(SqliteDbContext).Assembly);
#if DEBUG
Database.SetInitializer(new MyDbInitializer(Database.Connection.ConnectionString, modelBuilder));
#endif
}
}

5.配置Web.config:

默认的配置文件各种问题。可以直接拷贝项目中的测试用的配置文件。

<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
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=b77a5c561934e089" 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" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite"/>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
</configuration>

6.配置Global.asax:

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
using (var db = new SqliteDbContext())
{
}
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

查看生成的数据库:表映射、关系映射和索引都正确创建了。

调用一下:

代码已经上传到gitosc:http://git.oschina.net/myshare/SQLiteCodeFirst

EntityFramework系列:SQLite.CodeFirst自动生成数据库的更多相关文章

  1. MVC自动生成数据库【Code-FIrst方式】

    一般我们写好实体之后,配置好数据上下文对象,还有在配置文件中改好连接字符串之后. 还不能生成数据库,自动生成数据库,有两步关键步骤:   1.   Enable Migrations   2. Upd ...

  2. 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...

  3. MVC Code First 自动生成数据库

    1.新建一个MVC项目

  4. 自动生成数据库字典(sql2008)

    每次做项目的时候都要做数据字典,这种重复的工作实在很是痛苦,于是广找资料,终于完成了自动生成数据库字典的工作,废话少说,上代码. 存储过程: SET ANSI_NULLS ON GO SET QUOT ...

  5. 【工具篇】利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档

    对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...

  6. 基于数据库的自动化生成工具,自动生成JavaBean、自动生成数据库文档等(v4.1.2版)

            目录:            第1版:http://blog.csdn.net/vipbooks/article/details/51912143            第2版:htt ...

  7. atitit.自动生成数据库结构脚本,或者更换数据库,基于hibernate4

    atitit.自动生成数据库结构脚本,或者更换数据库,基于hibernate4 目前近况:: 更换数据库,但是是使用spring集成的. <!-- hibernate配置文件路径 --> ...

  8. 自动生成数据库字典(sql2008) 转自 飘渺の云海

    每次做项目的时候都要做数据字典,这种重复的工作实在很是痛苦,于是广找资料,终于完成了自动生成数据库字典的工作,废话少说,上代码. 截取一部分图片: 存储过程: SET ANSI_NULLS ON GO ...

  9. Mybatis总结之如何自动生成数据库表结构

    一般情况下,用Mybatis的时候是先设计表结构再进行实体类以及映射文件编写的,特别是用代码生成器的时候. 但有时候不想用代码生成器,也不想定义表结构,那怎么办? 这个时候就会想到Hibernate, ...

随机推荐

  1. JS简单加密

    //简单的jS加密解密//code为对应的字符串,h为(2,8,10,16)就是要转成的几进制function en(code, h) { var monyer = new Array();var i ...

  2. lucene-查询query->WildcardQuery使用通配符搜索

    Lucene也提供了通配符的查询,这就是WildcardQuery. package ch11; import org.apache.lucene.analysis.standard.Standard ...

  3. Spring Assert 断言

    Assert(断言)的初步理解构思 Web 应用在接受表单提交的数据后都需要对其进行合法性检查,如果表单数据不合法,请求将被驳回.类似的,当我们在编写类的方法时,也常常需要对方法入参进行合 法性检查, ...

  4. 多线程中的synchronized

    synchronized是Java中的关键字,是一种同步锁.它修饰的对象有以下几种: 1. 修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用的对象是调用这个代码 ...

  5. 【BZOJ-4548&3658】小奇的糖果&Jabberwocky 双向链表 + 树状数组

    4548: 小奇的糖果 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 103  Solved: 47[Submit][Status][Discuss] ...

  6. .net config文件 配置类的集合

    1,appconfig文件 <configSections> <section name="ToolConfig" type="DMTools.Tool ...

  7. JDK与Java SE/EE/ME的区别

    1. Java SE(Java Platform,Standard Edition). Java SE 以前称为 J2SE.它允许开发和部署在桌面.服务器.嵌入式环境和实时环境中使用的 Java 应用 ...

  8. 解析window.open链接的参数

    ); var arr = new Array(); arr = str.split("&"); ){ ; i<arr.length; i++){ ){ ); if(p ...

  9. [Android]Volley源码分析(二)

    上一篇介绍了Volley的使用,主要接触了Request与RequestQueue这两个类,这篇就来了解一下这两个类的具体实现. Request类图:

  10. JAva使用DOM读取XML数据(解析)

    原来一切都是有套路的 使用DOM解析XML文档步骤 1.创建解析器工厂对象 DocumentBuildFactory对象 2.由解析器工厂对象创建解析器对象,即DocumentBuilder对象 3. ...