EF之CodeFirst代码先行

来源:互联网 发布:淘宝卖家客服人工电话 编辑:程序博客网 时间:2024/05/14 04:35

    为了支持以设计为中心的开发流程,EF还更多地支持以代码为中心 (code-centric) ,我们称为代码优先的开发,代码优先的开发支持更加优美的开发流程,它允许你在不使用设计器或者定义一个 XML 映射文件的情况下进行开发。

  ·允许编写简单的模型对象POCO (plain old classes),而不需要基类。

  ·通过"约定优于配置",使得数据库持久层不需要任何的配置

  ·也可以覆盖"约定优于配置",通过流畅的 API 来完全定制持层的映射。

  Code First是基于Entity Framework的新的开发模式,原先只有Database First和Model First两种。Code First顾名思义,就是先用C#/VB.NET的类定义好你的领域模型,然后用这些类映射到现有的数据库或者产生新的数据库结构。Code First同样支持通过Data Annotations或fluent API进行定制化配置。

    下面我就来进行codeFirst的演示:

    先建立控制台程序:

    


   然后新建类:


   


   新建Customer,OrderInfo,以及 HotelDbContext类




  在编码前进行相应的引用,然后进行类的编码:

  

  


  Customer类:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace CodeFirst1{    public class Customer    {        public int Id { get; set; }        public string CusName { get; set; }        public virtual ICollection<OrderInfo> order { get; set; }    }}

   

   OrderInfo类:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ComponentModel.DataAnnotations;namespace CodeFirst1{    public class OrderInfo    {        [Key]        public int Id { get; set; }        public string content { get; set; }        /// <summary>        /// 外键        /// </summary>        public int customerId { get; set; }        public Customer Customer { get; set; }    }}

      这里要注意Key的主键的问题

  HotelDbContxt类的编写:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.Entity;namespace CodeFirst1{    public class HotelDbContext :DbContext    {        public HotelDbContext()            : base("name=ConnCodeFirst")        {        }        public DbSet<Customer> Customer { get; set; }        public DbSet<OrderInfo> OrderInfo { get; set; }    }}

     编写成功后加上一个配置文件用来连接数据库:




  配置文件的编写如下:

<?xml version="1.0" encoding="utf-8" ?><configuration>    <startup>      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />    </startup>  <connectionStrings>    <add name="ConnCodeFirst" connectionString="server=192.168.24.233;uid=sa;pwd=123456;database=CodeFirstDB"  providerName="System.Data.SqlClient" />  </connectionStrings></configuration>


     最后运行程序:


  

 数据库展示如下:


   


   三种EF的变现类型介绍完了,大家的EF框架是不是有很大的收获呢?也希望大家踊跃拍砖!


1 0