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 call与apply方法

    js中所有函数都默认定义了Call()与apply()两个方法,call与apply的第一个参数都是需要调用的函数对象,在函数体内这个参数就是this的值,剩余的参数是需要传递给函数的值,call与a ...

  2. jquery获取多重input的方式

    获取input的checked值是否为true: 第一种: if($("input[name=item][value='val']").attr('checked')==true) ...

  3. pch文件的使用

    pch文件的应用场景:1.用来定义一些全局的宏2.用来导入一些全局都能访问的头文件(如果只需要让.m或者.mm文件访问到,不需要让.c文件访问到,那么需要把头文件写到#ifdef _OBJC_ #en ...

  4. 快速提高 Xcode 编译速度的方法(转载自网上一个大神的方法)

    1.,中的 Debug Information Format 的选项中选择 DWARF ,平时调试就是用整个选项,经过测试,速度确实有很大的提升,等发行版本的时候在调回 DWARF with dsYM ...

  5. 【BZOJ-4422】Cow Confinement 线段树 + 扫描线 + 差分 (优化DP)

    4422: [Cerc2015]Cow Confinement Time Limit: 50 Sec  Memory Limit: 512 MBSubmit: 61  Solved: 26[Submi ...

  6. 【poj3017】 Cut the Sequence

    http://poj.org/problem?id=3017 (题目链接) 题意 给出一个数列要求将它分割成许多块,每块的数的和不超过m,要求每块中最大的数之和最小. Solution 这道题真的很不 ...

  7. waf2控件名

    1,查询表格(queryGrid),编辑表格(editGrid) wafGrid 2,快速F7 wafPromptQuick 3,表格F7 wafPromptGrid 4,自定义F7 wafPromp ...

  8. 数组、ArraryList和List三者的区别

    在C#中数组,ArrayList,List都能够存储一组对象,那么这三者到底有什么样的区别呢. 数组 数组在C#中最早出现的.在内存中是连续存储的,所以它的索引速度非常快,而且赋值与修改元素也很简单. ...

  9. Spring Cache 介绍

    Spring Cache 缓存是实际工作中非常常用的一种提高性能的方法, 我们会在许多场景下来使用缓存. 本文通过一个简单的例子进行展开,通过对比我们原来的自定义缓存和 spring 的基于注释的 c ...

  10. POJ 1659 Frogs' Neighborhood(Havel-Hakimi定理)

    题目链接: 传送门 Frogs' Neighborhood Time Limit: 5000MS     Memory Limit: 10000K Description 未名湖附近共有N个大小湖泊L ...