EntityFramework系列:SQLite.CodeFirst自动生成数据库
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自动生成数据库的更多相关文章
- MVC自动生成数据库【Code-FIrst方式】
		
一般我们写好实体之后,配置好数据上下文对象,还有在配置文件中改好连接字符串之后. 还不能生成数据库,自动生成数据库,有两步关键步骤: 1. Enable Migrations 2. Upd ...
 - 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】
		
原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...
 - MVC Code First 自动生成数据库
		
1.新建一个MVC项目
 - 自动生成数据库字典(sql2008)
		
每次做项目的时候都要做数据字典,这种重复的工作实在很是痛苦,于是广找资料,终于完成了自动生成数据库字典的工作,废话少说,上代码. 存储过程: SET ANSI_NULLS ON GO SET QUOT ...
 - 【工具篇】利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档
		
对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...
 - 基于数据库的自动化生成工具,自动生成JavaBean、自动生成数据库文档等(v4.1.2版)
		
目录: 第1版:http://blog.csdn.net/vipbooks/article/details/51912143 第2版:htt ...
 - atitit.自动生成数据库结构脚本,或者更换数据库,基于hibernate4
		
atitit.自动生成数据库结构脚本,或者更换数据库,基于hibernate4 目前近况:: 更换数据库,但是是使用spring集成的. <!-- hibernate配置文件路径 --> ...
 - 自动生成数据库字典(sql2008) 转自 飘渺の云海
		
每次做项目的时候都要做数据字典,这种重复的工作实在很是痛苦,于是广找资料,终于完成了自动生成数据库字典的工作,废话少说,上代码. 截取一部分图片: 存储过程: SET ANSI_NULLS ON GO ...
 - Mybatis总结之如何自动生成数据库表结构
		
一般情况下,用Mybatis的时候是先设计表结构再进行实体类以及映射文件编写的,特别是用代码生成器的时候. 但有时候不想用代码生成器,也不想定义表结构,那怎么办? 这个时候就会想到Hibernate, ...
 
随机推荐
- 初探psutil
			
系统性能信息模块psutil 1,psutil简介 psutil是一个跨平台能够轻松获取系统的进程和系统利用率,主要应用在系统监控,分析和限制系统资源以及进程管理.它实现了很多系统管理的命令,如ps, ...
 - Laplacian算子
			
多元函数的二阶导数又称为Laplacian算子: \[ \triangledown f(x, y) = \frac {\partial^2 f}{\partial x^2} + \frac {\par ...
 - Vim快捷键操作命令
			
Vim是一个超牛的编辑器,命令功能十分强大 .而且这些命令大都可以进行组合 ,比如,9yy命令表示复制9行内容,9表示要复制的行数,同样100dd表示删除100行,当数字和命令合作的时候,就比单纯的命 ...
 - 【BZOJ-2400】Spoj839Optimal Marks      最小割 + DFS
			
2400: Spoj 839 Optimal Marks Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 567 Solved: 202[Submit ...
 - BZOJ 1088 扫雷Mine
			
今天做了几道BZOJ的题,发现统观题目时还是很多很多都不会的,不过还是有几道时可以作的,以后要慢慢加强,争取多做题 BZOJ 1088 扫雷 其实本人平常不大玩扫雷的,就算玩也不是很好,不过看n*2的 ...
 - 【poj3615】 Cow Hurdles
			
http://poj.org/problem?id=3615 (题目链接) 题意 给出一张有向图,求从u到v最大边最小的路径的最大边.→_→不会说话了.. Solution 好久没写Floyd了,水一 ...
 - 【poj1017】 Packets
			
http://poj.org/problem?id=1017 (题目链接) 题意 一个工厂制造的产品形状都是长方体盒子,它们的高度都是 h,长和宽都相等,一共有六个型号,分别为1*1, 2*2, 3* ...
 - python统计nginx脚本信息
			
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import subprocess import th ...
 - Java命名约定
			
类名 类名应该是名词, 描述对象.应该按照驼峰式写法,即只有每个单词首字母大写. 接口名称 接口名称应该是形容词,描述功能.应该以“able”.“ible”结尾,否则应该是名词.通常遵循和类名写相同的 ...
 - POJ 2528 Mayor's posters(线段树/区间更新  离散化)
			
题目链接: 传送门 Mayor's posters Time Limit: 1000MS Memory Limit: 65536K Description The citizens of By ...