使用简介

 

序言

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

建立一个简单的Model

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

 2.右键选择新增实体架构

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

4.添加标量属性this

 

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

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

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

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

 它是怎么工做的

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的时候才去查询以后将结果存放在内存中对数据进行不通过数据库直接从中读取,总之当前能够认为它是用到的时候才去执行,详细的流程待后续学习在进行总结。