码迷,mamicode.com
首页 > 其他好文 > 详细

Entity Framework之Code First

时间:2015-08-17 01:09:53      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:entity framework   code first   

       EF(Entity Framework )是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping (对象关系映射(Object RelationalMapping,简称ORM)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。)) 解决方案。

         Entity Framework利用了抽象化数据结构的方式,将每个数据库对象都转换成应用程序对象 (entity),而数据字段都转换为属性 (property),关系则转换为结合属性(association),让数据库的 E/R 模型完全的转成对象模型。它有三种生成模式,分别为Database First、Model First、CodeFirst,那么今天我们就来实现Code First。所谓Code First就是说用代码来直接去创建数据库并进行EF映射。

首先我们先来添加两个实体类,代码如下:

订单类

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; }
    }


客户类

 

public class Customer
    {
       [Key]
       public int Id {get;set;}
 
       public string CusName { get; set; }
 
       public virtualICollection<OrderInfo> Order { get; set; }
    }

这里的[Key]是标识符的意思,也就是设定主键,这里要添加引用System.ComponentModel.DataAnnotations

接下来我们就自定义一个数据库上下文

public classHotelDbContext:DbContext
    {
       public HotelDbContext()
           :base("name=ConnCodeFirst")
        { }
        public DbSet<Customer> Customer {get; set; }
 
        public DbSet<OrderInfo> OrderInfo{ get; set; }
    }


要能继承DbContext类,就要添加System.Data.Entity,即引用在我们程序目录下的packages\EntityFramework.5.0.0\lib\net40\EntityFramework.dll

下面来写下配置文件

<?xmlversion="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ConnCodeFirst"connectionString="server=.;uid=sa;pwd=1;database=CodeFirstDemoDb"providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>


要注意的是我们命名的字符串变量一定要和数据库上下文类中的变量名一致。

客户端程序

class Program
    {
        static void Main(string[] args)
        {
            HotelDbContext dbcontext = newHotelDbContext();
           dbcontext.Database.CreateIfNotExists();//如果数据库不存在,创建数据库
        }
    }


执行,看看你的数据库中有没有添加成功吧!

后记

学习EF从代码构建来实践会有更加不一样的体会,逻辑也更清晰了一些,三种构建方法我们都应该去实践一下,这样才能学好EF

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

Entity Framework之Code First

标签:entity framework   code first   

原文地址:http://blog.csdn.net/xfz0330/article/details/47709093

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!