惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
Simon Willison's Weblog
Simon Willison's Weblog
H
Help Net Security
F
Fortinet All Blogs
H
Heimdal Security Blog
S
Schneier on Security
L
LangChain Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
NISL@THU
NISL@THU
P
Palo Alto Networks Blog
J
Java Code Geeks
博客园 - 【当耐特】
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Vulnerabilities – Threatpost
I
InfoQ
Recorded Future
Recorded Future
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
CERT Recently Published Vulnerability Notes
T
Tenable Blog
腾讯CDC
C
Check Point Blog
量子位
M
MIT News - Artificial intelligence
GbyAI
GbyAI
罗磊的独立博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog
小众软件
小众软件
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
V2EX - 技术
V2EX - 技术
T
Threatpost
Engineering at Meta
Engineering at Meta
Attack and Defense Labs
Attack and Defense Labs
T
Tailwind CSS Blog
S
Securelist
The Cloudflare Blog
博客园 - 叶小钗
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿

博客园 - Henry Cui

招聘高级.Net工程师 Node.js Web开发(二)认识Express(上) Node.js Web开发(一)从零开始 Html5 Step by Step(二) 本地存储 HTML 5 Step by Step(一) 拖放API Git学习笔记(一)初识Git DDD中的Specification模式 Silverlight 4之旅(三)数据绑定(中) Silverlight 4之旅(二)数据绑定(上) Silverlight 4之旅(一) .Net 4.0 Parallel 编程之旅 .Net 4.0 Parallel 编程(九)Task中的数据共享(下) .Net 4.0 Parallel编程(八)Task中的数据共享(中) .Net 4.0 Parallel 编程(七)Task中的数据共享(上) .Net 4.0 Parallel 编程(六)Task(下) .Net 4.0 Parallel 编程(五)Task(中) .Net 4.0 Parallel 编程(四) Task(上) Entity Framework Code-First(下) Entity Framework POCO T4模板使用
Entity Framework Code-First(上)
Henry Cui · 2010-07-25 · via 博客园 - Henry Cui

2010-07-25 14:42  Henry Cui  阅读(11004)  评论()    收藏  举报

在7.14号微软ado.net团队发布了EF Feature CTP4,在ctp4中code-first得到了很大的加强,支持了很多属性。本篇文章中就code-first进行一些尝试。

准备

1.下载ctp4:Entity Framework Feature CTP4.

2.准备我们的工程:

image

各个项目之间的关系以及作用就不必多说了。

创建Model

我们建立一个employee、department的model。employee:

    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public int DepartmentID { get; set; }

        public virtual Department Department { get; set; }

    }

Department:

    public class Department
    {
        public int DepartmentID { get; set; }
        public string DepartName { get; set; }

        public virtual ICollection<Employee> Employees { get; set; }
    }

创建Context

在context项目中,我们建立一个NorthwindContext,让它继承与DbContext。别忘了添加对ctp4的引用image

NorthwindContext:

    public class NorthwindContext:DbContext
    {
        public NorthwindContext()
            : base()
        { }

        public NorthwindContext(string connName)
            : base(connName)
        { }

        public DbSet<Employee> Employees { get; set; }

        public DbSet<Department> Departments { get; set; }
    }

测试方法

我们添加如下的数据链接:

  <connectionStrings>
    <add name="EFCTP" connectionString="Data Source=HENRYCUI-PC;Initial Catalog=EFCTP;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

测试方法:

        [TestMethod]
        public void CodeFirstTest()
        {
            using (var context = new NorthwindContext("EFCTP"))
            {
                context.Departments.Add(new Department()
                {
                    DepartName="IT"
                });
                context.SaveChanges();
                Assert.AreEqual(1,context.Departments.Count());
            }
        }

在测试之前我们看些我的数据库中:

image

并不存在EFCTP数据库。运行测试方法:

image

我们看看数据库中:

image

看到已经帮我们创建好了数据库EFCTP,并且已经建好了表Departments,Employees,以及主键关系跟外键关系。

使用Data Annotations

其实在上面的示例中让我们感到惊讶的是,不但自动帮我们建立好了数据库以及表,就连表里面的主键、外键也帮我们建立好了。默认的时候,code-frist库会生成一个跟我们contex名字一样的数据库,而且会在./SQLEXPRESS下面。下面就说下有关主键以及外键的默认生成:
1)Primary Key:code-fist将我们定的类中属性名为ID或则classname+ID的属性默认设置为主键(上面示例中的EmployeeID、DepartmentID),如果这个属性被定义为int 、long、short那么将设置为identity 列。

2)Relationship:code-first会通过定义的类型之间的引用关系推算出外键的关系,但是这只是在两个类型中只有一个导航属性的时候才会检测出来,当两个类型中存在多个导航属性时,那就检测不出来了。

当我们需要定义一些跟默认的检测不一样的东西的时候,我们可以使用Data Annotations进行显示的标识。对于Data Annotation的使用大家可能不会陌生的,在RIA Service也有使用。在Entity Framework ctp3中已经包含了Data Annotaions。我们看一下Data Annotaions会提供了那些标识给Entity Framework 使用呢:

  • Key

  • StringLength

  • ConcurrencyCheck

  • Required

  • Timestamp

  • DataMember

  • RelatedTo

  • MaxLength

  • StoreGenerated

我们修改下前面定义的几个实体,使用Data Annotaions进行标识,首先需要添加System.ComponentModel.DataAnnotations的引用。

Employee.cs:

    public class Employee
    {
        [Key]
        public int EmployeeID { get; set; }
        [Required]
        [StringLength(50,ErrorMessage="FirstName can't over 50 chars")]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }

        public int Age { get; set; }
        public int DepartmentID { get; set; }

        [RelatedTo(ForeignKey = "FK_EmDepartment", Property = "Department")]
        public virtual Department Department { get; set; }

    }

总结

本文中介绍了下entity framework ctp 4中的code-first的功能,希望对您有用。其实在ctp4中提供了另外的一种方式去实现Data Annotaions的功能,以及如果我们的定义类型发生改变的时候怎么办呢?在下篇文中会介绍下其他部分的内容。

参考文献

1.Conventions for Code First

2.Data Annotations in the Entity Framework and Code First