序言

在这一篇中,我们将演示EnitityFramework基本的建模【建模也是EntityFramework最核心的特性】范例,例如实体的分离和继承等。我们开始了演示如何创建一个简单的概念模型的例子,然后让EnitityFramework建立底层数据库。在余下的例子中,我们将告诉你如何从现有的表和数据库关系创建模型。

创建一个简单的Model

1.点击添加新建项,选择Data下的ADO.NET实体模型,并选择空模型。

2.右键选择新增实体

3.将实体命名为Person,实体集命名为People,添加名为Id,类型为Int32的键属性。

4.添加标量属性

5.添加标量属性FirstName. LastName, MiddleName,PhoneNumber,同时指定键属性Id的数据库生成策略

6.空白处右键-->属性,修改实体容器名称为EF6RecipesContext,数据库架构名称为article2,这些都是为更好地管理Model做的有意义的动作。

7.右键选择根据模型生成数据库,选择创建新的连接,选择目标数据库

8.在.edmx文件中生成仓储模型,并运行数据库脚本

它是怎么工作的

using System;

namespace EntityFrameworkDemo
{
class Program
{
static void Main()
{
using (var context=new EF6RecipesContext())
{
var person = new Person
{
FirstName = "Robert",
MiddleName = "Allen",
LastName = "Doe",
PhoneNumber = "867-5309"
};
context.People.Add(person);
person = new Person
{
FirstName = "John",
MiddleName = "K.",
LastName = "Smith",
PhoneNumber = "824-3031"
};
context.People.Add(person);
person = new Person
{
FirstName = "Billy",
MiddleName = "Albert",
LastName = "Minor",
PhoneNumber = "907-2212"
};
context.People.Add(person);
person = new Person
{
FirstName = "Kathy",
MiddleName = "Anne",
LastName = "Ryan",
PhoneNumber = "722-0038"
};
context.People.Add(person);
context.SaveChanges();
}
using (var context=new EF6RecipesContext())
{
foreach (var person in context.People)
{
Console.WriteLine("{0} {1} {2}, Phone: {3}",
person.FirstName, person.MiddleName,
person.LastName, person.PhoneNumber);
}
}
Console.ReadKey();
}
}
}

运行效果

至于使用using的好处,这里就不多说了,因为这也是最基础的。下面是书中的解释片段,不熟悉的同学可以看看

There are a few nice features of using()statements. First, when the code execution leaves the using() {}block,
the Dispose()method on the context will be called because DbContext implements the IDisposable interface. For
DbContext, the Dispose()method closes any active database connections and properly cleans up any other resources
that need to be released.
     Second, no matter how the code leaves the using(){}block, the Dispose()method is called. Most importantly,
this includes return statements and exceptions that may be thrown within the code block. The using(){}block is kind
of a guarantee that critical resources will be reclaimed properly.
  The best practice here is always to wrap your code in the using(){}block when creating new instances of
DbContext. It’s one more step to help bulletproof your code

从已存在的数据库中生成模型

问题

现有一个已存在的数据库中的表,假设也有一些视图,已经一些外键约束,你想为这个数据库创建模型

解决方案

你的数据库中的结构可能是这样:

首先我们安装前面的步骤,打开向导,选择由数据库生成,并选择需要操作的表和视图

点击完成后,EntityFramework会推断出Poet和Poem,以及Meter和Poem之间一对多的关系

从模型浏览器中我们可以看出一首诗对应一个作者和一个分类,分别对应Poet和Meter导航属性,如果我们有一个Poem的实体,那么导航属性Poet也会包含一个诗人的实体的集合【因为是一对多的关系】,同理Meter也是如此。因为SQLSERVER不支持在视图上定义关系,因此vwLiberary上市一组空的导航属性

它是怎么工作的

using (var context = new EF6RecipesEntities())
{
var poet = new Poet {FirstName = "John", LastName = "Milton"};
var poem = new Poem {Title = "Paradise Lost"};
var meter = new Meter {MeterName = "Iambic Pentameter"};
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
poem = new Poem {Title = "Paradise Regained", Meter = meter, Poet = poet};
context.Poems.Add(poem);
poet = new Poet {FirstName = "Lewis", LastName = "Carroll"};
poem = new Poem {Title = "The Hunting of the Shark"};
meter = new Meter {MeterName = "Anapestic Tetrameter"};
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
poet = new Poet {FirstName = "Lord", LastName = "Byron"};
poem = new Poem {Title = "Don Juan", Meter = meter, Poet = poet};
context.Poems.Add(poem);
context.SaveChanges();
}
using (var context = new EF6RecipesEntities())
{
var poets = context.Poets;
foreach (var poet in poets)
{
Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName);
foreach (var poem in poet.Poems)
{
Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName);
}
} }
// using our vwLibrary view
using (var context = new EF6RecipesEntities())
{
var items = context.vwLibraries;
foreach (var item in items)
{
Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
Console.WriteLine("\t{0} ({1})", item.Title, item.MeterName);
}
}

运行效果

我们使用SQLSERVER profile监视这段代码的执行情况发现,并不是执行完var poets = context.vwLibraries;就立即去数据库中抓取数据,而知在执行foreach的时候才去查询之后将结果存放在内存中对数据进行不经过数据库直接从中读取,总之当前可以认为它是用到的时候才去执行,详细的流程待后续学习在进行总结。

使用简介<EntityFramework6.0>的更多相关文章

  1. 分割一个表到多个实体<EntityFramework6.0>

    声明方式 public class Photograph { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public in ...

  2. 继承映射关系 TPH、TPT、TPC<EntityFramework6.0>

    每个类型一张表[TPT] 声明方式 public class Business { [Key] public int BusinessId { get; protected set; } public ...

  3. 将一个实体数据保存到不同的数据表中<EntityFramework6.0>

    2014-11-22声明方式 public class Product { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public ...

  4. 自连接<EntityFramework6.0>

    自引用 public class PictureCategory { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ...

  5. 多对多关系<EntityFramework6.0>

    无负载建立多对多关联的模型 原文中是Modeling a Many-to-Many Relationship with No Payload,虽然这么翻译也有点不准确,但是可以说明其目的,如下图所示, ...

  6. EntityFramework6.0的Sql读写分离拦截器 和 MVC的 Action拦截器 对比

    EF的DbCommandInterceptor类 拦截: EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Int ...

  7. 升级实体框架EntityFramework6.0

    首先安装nuget 管理器 https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca 安装 ...

  8. 序言<EntityFramework6.0>

    Entity Framework是微软战略性的数据访问技术,不同与早期访问技术,Entity Framework并不耦合在Visual Studio中,它提供了一个全面的, 基于模型的生态系统,使您能 ...

  9. JSON简介——(0)

    JSON: JavaScript Object Notation(JavaScript 对象表示法) JSON 是存储和交换文本信息的语法.类似 XML. JSON 比 XML 更小.更快,更易解析. ...

随机推荐

  1. unity之自制玻璃啤酒瓶shader

    客户的要求如下 步骤: 1.进行玻璃瓶效果分析 效果如下:高光,类次表面散射(里层通透而外层较为暗淡),外层白色勾勒轮廓. 高光:unity内部提供光滑度参数,越光滑则高光效果越明显,啤酒瓶材质是属于 ...

  2. effective java 学习心得

    目的 记录一下最主要学习心得,不然凭我这种辣鸡记忆力分分钟就忘记白看了... 用静态工厂方法代替构造器的最主要好处 1.不必每次都创建新的对象 Boolean.valueOf Long.valueOf ...

  3. String StringBuffer StringBuilder

    package com.test; import java.util.Date; /*** * * // 输出的结果是:// 来一个测试// 来一个测试如果只输出这句就证明了String是不可变的// ...

  4. linux vi(vim)常用命令汇总

    1 查找 /xxx(?xxx) 表示在整篇文档中搜索匹配xxx的字符串, / 表示向下查找, ? 表示向上查找其中xxx可以是正规表达式,关于正规式就不多说了. 一般来说是区分大小写的, 要想不区分大 ...

  5. C#进阶目录

    一.Sql语句的性能优化 二.Quartz.NET的介绍 三.Log4.Net的介绍 四.Topshelf的介绍 五.Git的使用 六.IEnumerable接口迭代原理 七.Lambada表达式的演 ...

  6. gitlab使用个人版v16.11

    title: gitlab使用个人版v16.11 date: 2016-11-13 20:53:00 tags: [gitlab] --- 1.安装gitbash 附上地址链接:git 2.配置git ...

  7. Java的国际化(i18n)

    http://blog.csdn.net/csuliky/article/details/4225800 1. Java国际化简介 Java既然作为一个跨平台的语言就必然要在各种不同的语言环境中使用, ...

  8. 跟着百度学PHP[6]超级全局变量

    超级全局变量在PHP 4.1.0之后被启用, 是PHP系统中自带的变量,在一个脚本的全部作用域中都可用. 参考文献:http://www.runoob.com/php/php-superglobals ...

  9. 【Python文件处理】递归批处理文件夹子目录内所有txt数据

    因为有个需求,需要处理文件夹内所有txt文件,将txt里面的数据筛选,重新存储. 虽然手工可以做,但想到了python一直主张的是自动化测试,就想试着写一个自动化处理数据的程序. 一.分析数据格式 需 ...

  10. BUG-FREE-For Dream

    一直直到bug-free.不能错任何一点. 思路不清晰:刷两天. 做错了,刷一天. 直到bug-free.高亮,标红. 185,OA(YAMAXUN)--- (1) findFirstDuplicat ...