开篇之前感谢 china_fucan的文章给我的帮助,下面的评论也解决了很多问题同样给予感谢.

code first

项目中的ORM框架如果采用的是EF,那么可能会采用code first的方式去使用EF.就是先将数据库的实体类,以及EF的核心DBContext写好之后, 运行程序会通过特定的数据库链接字符串在数据库中生成相应的table或数据.

创建一个code first demo

  • 使用vs新建一个console app
  • 创建一个class命名为Ef6RecipesContext,并且继承自DbContext.
using System.Data.Entity;
using DennisEFDemo.CodeFirstDemo.DBModels; namespace DennisEFDemo.CodeFirstDemo.DBContext
{
public class Ef6RecipesContext : DbContext
{
public DbSet<PictureCategory> PictureCategories { get; set; }
public Ef6RecipesContext()
: base("name=EF6CodeFirstRecipesContext")
{
}
/// <summary>
/// 在EF6RecipesContext中重写方法OnModelCreating配置双向关联(ParentCategory 和 SubCategories)
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PictureCategory>().HasMany(t => t.Subcategories).WithOptional(t => t.ParentCategory);
}
}
}
  • 创建DB models PictureCategory
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; namespace DennisEFDemo.CodeFirstDemo.DBModels
{
[Table("PictureCategory", Schema = "dbo")]
public class PictureCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; private set; }
public string Name { get; set; }
public int? ParentCategoryId { get; private set; }
[ForeignKey("ParentCategoryId")]
public virtual PictureCategory ParentCategory { get; set; } //书中没有virtual关键字,这会导致导航属性不能加载,后面的输出就只有根目录!!
public virtual List<PictureCategory> Subcategories { get; set; }
public PictureCategory()
{
Subcategories = new List<PictureCategory>();
}
}
}
  • 在main函数中写一个静态方法
class Program
{
static void Main(string[] args)
{
RunExample();
Console.ReadKey(); } static void RunExample()
{
using (var context = new Ef6RecipesContext())
{
var louvre = new PictureCategory { Name = "Louvre" };
var child = new PictureCategory { Name = "Egyptian ANTIQUITéS" };
louvre.Subcategories.Add(child);
child = new PictureCategory { Name = "Sculptures" };
louvre.Subcategories.Add(child);
child = new PictureCategory { Name = "Paintings" };
louvre.Subcategories.Add(child);
var paris = new PictureCategory { Name = "Paris" };
paris.Subcategories.Add(louvre);
var vacation = new PictureCategory { Name = "Summer Vacation" };
vacation.Subcategories.Add(paris);
context.PictureCategories.Add(paris);
context.SaveChanges();
}
using (var context = new Ef6RecipesContext())
{
var roots = context.PictureCategories.Where(c => c.ParentCategory == null);
roots.ToList().ForEach(root => Print(root, 0));
}
}
static void Print(PictureCategory cat, int level)
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("{0}{1}", sb.Append(' ', level).ToString(), cat.Name);
cat.Subcategories.ForEach(child => Print(child, level + 1));
}
}
  • 修改app.config文件(如果是web工程则为web.config)
<connectionStrings>
<add name="EF6CodeFirstRecipesContext" connectionString="Data Source=stcav-235\stcav235;initial catalog=EF6Recipes;user id=sa;password=`*******`;" providerName="System.Data.SqlClient" />
</connectionStrings>
  • 运行程序,会在数据库中创建相应的table并将数据写入后读取输出到控制台.

  • 源代码我会上传到git上,链接.

DBModelBuilder

上述代码中的Ef6RecipesContext类中有个DBModelBuilder,我查了一下文档, 一般使用这个类的EF项目基本上都是CODE FIRST approach.解释一下这玩意:

DbModelBuilder用于将CLR类映射到数据库模型.

这种以代码为中心的构建实体数据模型(EDM)模型的方法称为“代码优先(code first)”

DbModelBuilder通常用于通过重写DbContext.OnModelCreating(DbModelBuilder)来配置模型

还可以独立于DbContext使用DbModelBuilder来构建模型

但是,推荐的方法是在DbContext中使用OnModelCreating, 优点是工作流程更直观,可以处理常见任务,例如缓存创建的模型。形成模型的类型在DbModelBuilder中注册,可选配置,可以通过将数据注释应用于您的类和使用流畅的样式DbModelBuilder来执行API。

目前先写到这儿,上述内容有误还请点击下方图标联系我, 如有新内容会继续对此文进行更新,有兴趣的话可以保持关注.

【Entity framework】Code First Approach的更多相关文章

  1. 【Entity Framework】Model First Approach

    EF中的model first 所谓mf, 就是使用vs提供的edm designer去设计model,然后将设计好的model使用vs在指定的数据库中生成数据库即可. 当你的项目既没有数据库也没有c ...

  2. 【Entity Framework】 Entity Framework资料汇总

    Fluent API : http://social.msdn.microsoft.com/Search/zh-CN?query=Fluent%20API&Refinement=95& ...

  3. 【Entity Framework】Revert the database to specified migration.

    本文涉及的相关问题,如果你的问题或需求有与下面所述相似之处,请阅读本文 [Entity Framework] Revert the database to specified migration. [ ...

  4. 【Entity Framework】disable automatic migration, 执行update-migration仍然会显示有automatic migration

    本文涉及的相关问题,如果你的问题或需求有与下面所述相似之处,请阅读本文 [Entity Framework] disable automatic migration, 执行update-migrati ...

  5. 【Entity Framework】初级篇--ObjectContext、ObjectQuery、ObjectStateEntry、ObjectStateManager类的介绍

    本节,简单的介绍EF中的ObjectContext.ObjectQuery.ObjectStateEntry.ObjectStateManager这个几个比较重要的类,它们都位于System.Data ...

  6. 【极力分享】[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例【转载自https://segmentfault.com/a/1190000004152660】

      [C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例 本文我们来学习一下在Entity Framework中使用Cont ...

  7. AppBox升级进行时 - 拥抱Entity Framework的Code First开发模式

    AppBox 是基于 FineUI 的通用权限管理框架,包括用户管理.职称管理.部门管理.角色管理.角色权限管理等模块. 从Subsonic到Entity Framework Subsonic最早发布 ...

  8. Entity Framework 6 Code First新特性:支持存储过程

    Entity Framework 6提供支持存储过程的新特性,本文具体演示Entity Framework 6 Code First的存储过程操作. Code First的插入/修改/删除存储过程 默 ...

  9. 创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

    创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添 ...

随机推荐

  1. 即时通信系统中实现聊天消息加密,让通信更安全【低调赠送:C#开源即时通讯系统(支持广域网)——GGTalk4.5 最新源码】

    在即时通讯系统(IM)中,加密重要的通信消息,是一个常见的需求.尤其在一些政府部门的即时通信软件中(如税务系统),对即时聊天消息进行加密是非常重要的一个功能,因为谈话中可能会涉及到机密的数据.我在最新 ...

  2. .net web site 和 web application 的区别

    web application 会把所有的代码编译打包成单一的库文件(.dll). web site 不会对整个的代码进行编译,在运行时须要哪一段代码就编译哪段代码.这导致web site 上线后,如 ...

  3. over(partition by)开窗函数的使用

    开窗函数是分析函数中的一种,开窗函数与聚合函数的区别是:开窗函数是用于计算基于组的某种聚合值且每个的组的聚合计算结果可以有多行,而聚合函数每个组的聚合计算结果只有一个.使用开窗函数可以在没有group ...

  4. NGINX的几个应用场景

    NGINX的几个应用场景 两个参考地址: NGINX的百度百科:https://baike.baidu.com/item/nginx/3817705?fr=aladdin NGINX的中文网站:htt ...

  5. 转:Process类的使用

    转载自:http://www.oschina.net/code/snippet_119226_6188 一.根据进程名获取进程的用户名? 需要添加对 System.Management.dll 的引用 ...

  6. .net core创建项目(指令方式)

    所谓的指令创建项目,就是不用再已安装的VS2015的环境下或者VS Core下创建,直接通过DOS指令创建也是OK的. 1.找到你所准备保存项目的项目文件夹(你也可以到某个目录用指令创建项目文件夹[  ...

  7. Java开发学习教程之对象的创建与使用

    java面向对象中的对象创建与使用.类是对象的抽象,为对象定义了属性和行为,但类本身既不带任何数据,也不存在于内存空间中.而对象是类的一个具体存在,既拥有独立的内存空间,也存在独特的属性和行为,属性还 ...

  8. echarts遇到的问题

    X轴无偏移: axisTick: { alignWithLabel: true }, x轴显示所有数据项且避免拥挤在xAxis设置: axisLabel: { interval: 0, rotate: ...

  9. Google翻译实现

    https://blog.csdn.net/yingshukun/article/details/53470424 Google翻译实现

  10. linux的/etc/passwd、/etc/shadow、/etc/group和/etc/gshadow—关于用户和组的配置文件

    1./etc/passwd  存储用户信息 [root@oldboy ~]# head /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bi ...