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
- EF之CodeFirst代码先行
- EF| CodeFirst 代码先行
- EF之概念先行
- 【EF系列】CodeFirst代码优先
- EF之ModelFirst实体先行
- EF之DBFirst数据库先行
- EF框架之CodeFirst创建数据库
- C# 之 EF CodeFirst创建MySQL数据库
- MVC3教程之实体模型和EF CodeFirst
- MVC3教程之实体模型和EF CodeFirst
- EF-CodeFirst创建步骤
- EF CodeFirst 级联删除
- EF codefirst数据迁移
- EF基础框架-codefirst
- EF——CodeFirst
- EF codefirst 数据库迁移
- EF-CodeFirst模式
- EF CodeFirst 数据库迁移
- android eclipse gradle 构建 出现 Could not create plugin of type 'AppPlugin' 等错误
- EF之ModelFirst实体先行
- HDU-2150 Pipe(math叉乘判断)
- android国际化(多语言)
- Git Step by Step (7):Git远程仓库(续)
- EF之CodeFirst代码先行
- Swift 1.1语言函数参数的特殊情况本地参数名外部参数名
- 用户模式下线程同步
- Jquery .ajax方法分析
- VectorDrawable-第二章
- PyQt4 tutorial读书笔记(6)-- widgets
- 当厌倦测试时,你可以做的16件事
- Git Step by Step (8):Git的merge和rebase
- iOS音频播放 (二):AudioSession