Entity Framework:代码优先
一、代码优先Code First
EF6支持Oracle ODT 12C Release 3 (net4.5)
DataModel(类)——》生成数据库DB
或
存在的数据库DB——》生成的数据模型(类)
二、创建或生成Model代码
(可利用Entity FrameWork Power Tools 生成Model代码)
先安装EFTools6.1ForVS2012 ,EF6.1版以上用EntityFramework.CodeTeplates.Csharp及自带的模板。
方式1、使用标注
/// <summary>
/// 景点类
/// </summary>
[Table("DESTINATIONS", Schema = "PAMS")]
public class Destination
{
[Column("DESTINATIONID", TypeName = "INT")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DestinationId { get; set; } [Column("NAME")]
public string Name { get; set; } [Column("COUNTRY")]
public string Country { get; set; } [Column("DESCRIPTION")]
public string Description { get; set; } [Column("PHOTO")]
public byte[] Photo { get; set; } public virtual List<Lodging> Lodgings { get; set; }
} /// <summary>
/// 住宿类
/// </summary>
[Table("LODGINGS", Schema = "PAMS")]
public class Lodging
{
[Column("LODGINGID", TypeName = "INT")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int LodgingId { get; set; } [Column("NAME")]
public string Name { get; set; } [Column("OWNER")]
public string Owner { get; set; } [Column("TARDESTINATIONID", TypeName = "INT")]
public int? DestinationID { get; set; } [ForeignKey("DestinationID")]
public Destination Destination { get; set; }
} /// <summary>
/// 度假村类
/// </summary>
public class Resort : Lodging
{
[Column("ENTERTAINMENT")]
public string Entertainment { get; set; }
} /// <summary>
/// 宿舍类
/// </summary>
public class Hostel : Lodging
{
[Column("MAXROOM", TypeName = "INT")]
public int? MaxRoom { get; set; }
}
方式2:使用模板Builder
public class BreakAwayContext : DbContext
{
public DbSet<CodeFirst.Model.Destination> Destinations { get; set; }
public DbSet<CodeFirst.Model.Lodging> Lodgings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationMap());
modelBuilder.Configurations.Add(new LodgingMap());
}
}
public class DestinationMap : EntityTypeConfiguration<CodeFirst.Model.Destination>
{
public DestinationMap()
{
this.HasKey(t => t.DestinationId);
Property(d => d.Name).IsRequired();
Property(d => d.Description).HasMaxLength();
} }
public class LodgingMap : EntityTypeConfiguration<CodeFirst.Model.Lodging>
{
public LodgingMap()
{
this.HasKey(t => t.LodgingId);
Property(d => d.Name).IsRequired();
Property(d => d.Owner).HasMaxLength();
this.Map<Lodging>(d => d.Requires("TYPE").HasValue("Standard"));
this.Map<Resort>(d => d.Requires("TYPE").HasValue("Resort"));
this.Map<Hostel>(d => d.Requires("TYPE").HasValue("Hostel"));
}
}
三、配置文件
<connectionStrings>
<add name=”BreakAwayContext ”, conectionstring=”” providerName=””>
</connectionStrings>
四、操作
1、添加
var destination = new CodeFirst.Model.Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
if (context.Destinations.Count((t => t.Name == "Bali") < )
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
2、修改
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var canyon = (from d in context.Destinations where d.Name == "Bali" select d).Single();
canyon.Description = "227 mile long canyon.";
context.Entry(gw)=EntityState.Modified;
context.SaveChanges();
}
3、删除
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
//var toDelete = new CodeFirst.Model.Destination { d.Name="Bali"};
//context.Destinations.Attach(toDelete); //attach,状态由added改为unchanged
//context.Destinations.Remove(toDelete);
//context.SaveChanges(); context.Database.ExecuteSqlCommand("delete from pams.DESTINATIONS where Name='Bali'");//直接执行sql, }
五、查询
1、Load方法把数据加载到内存(LINQ写法,同foreach)
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var query = from d in context.Destinations where d.Country == "Australia" select d;
query.Load();// foreach 也可以
var count = context.Destinations.Local.Count;
}
2、ToList()一次性从数据库中查出数据
var Invoices=ctx.Invoie.ToList();
foreach(var result in Onvoices)
{.}
3、Find方法根据键值先从内存中查询,内存中没有才查询数据库。
var destination = context.Destinations.Find();
4、Single(),SingleOrDefault(),First()等可根据条件直接从数据库查。
var destination = context.Destinations.SingleOrDefault(d => d.Name == "Bali");
六、直接执行SQL语句
1、context.Database.ExecuteSqlCommand("delete from pams.DESTINATIONS where Name='Bali'");//直接执行sql,
2、 IEnumerable<Lodging> a=context.Database.SqlQuery(“Select * from ..”) 可直接转为定义的实体类型,任何类型,EF不跟踪
3、DbSqlQuery<Lodging> c=context.Lodging.SqlQuery(“select* from ..) EF跟踪返回的对象。
4、modelBuilder.Entity<singleEntity>().HasEntitySetName(“MyEntity”) 创建实体集不需要在DBContext中定义
IEnumerable<Lodging> a=(Context as IObjectContextAdapter).ObjectContext.CreateQuery<Lodging>(“select * from ..”) 这以后的linq查询条件可合并为一个SQL
Entity Framework:代码优先的更多相关文章
- Entity Framework 代码先行
一.什么是Code First 为了支持以设计为中心的开发流程,EF还更多地支持以代码为中心 (code-centric) ,我们称为代码优先的开发,代码优先的开发支持更加优美的开发流程,它允许你在不 ...
- Linq to Entities,ADO.NET Entity Framework 模型优先
一.概念: Database First(数据库优先):存在的DB------------->生成Data Model .edmx文件 Model First(模型优先):Data Model ...
- Entity Framework 代码先行之约定配置
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- C# ORM—Entity Framework 之Code first(代码优先)(二)
一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...
- Entity Framework Code first(转载)
一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...
- Entity Framework 6.X实现记录执行的SQL功能
Entity Framework在使用时,很多时间操纵的是Model,并没有写sql语句,有时候为了调试或优化等,又需要追踪Entity framework自动生成的sql(最好还能记录起来,方便出错 ...
- 使用Entity Framework 4进行代码优先开发
[原文地址]Code-First Development with Entity Framework 4 .NET 4随带发布了一个改进版的Entity Framework(EF)- 一个位于Sy ...
- Entity Framework 之Database first(数据库优先)&Model First(模型优先)
一.什么是Entity Framework 1.1 实体框架(EF)是一个对象关系映射器,使.NET开发人员使用特定于域的对象与关系数据.它消除了需要开发人员通常需要编写的大部分数据访问代码.简化了原 ...
- C# ORM—Entity Framework 之Database first(数据库优先)&Model First(模型优先)(一)
一.什么是Entity Framework 1.1 实体框架(EF)是一个对象关系映射器,使.NET开发人员使用特定于域的对象与关系数据.它消除了需要开发人员通常需要编写的大部分数据访问代码.简化了原 ...
随机推荐
- [转载]二叉树(BST,AVT,RBT)
二叉查找树(Binary Search Tree)是满足如下性质的二叉树:①若它的左子树非空,则左子树上所有结点的值均小于根结点的值:②若它的右子树非空,则右子树上所有结点的值均大于根结点的值:③左. ...
- [转]MVC Razor模板引擎 @RenderBody、@RenderPage、@RenderSection及Html.RenderPartial、Html.RenderAction
本文参考自下面文章整理 MVC Razor模板引擎 @RenderBody.@RenderPage.@RenderSection及Html.RenderPartial.Html.RenderActio ...
- 读取excel的方法(可用于批量导入)
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); //1. Reading from a binary ...
- 阿里云服务器(Ubuntu16.04 64位)远程连接
购买阿里云服务器 1.打开阿里云官方网站,账号登录,选择产品中的云服务器 ECS 2.根据自身需求,选择合适的阿里云服务器系统,(1)点击一键购买,(2)选择地域,(3)根据自身需求,选择系统,这里选 ...
- 转【js & jquery】遮罩层实现禁止a、span、button等元素的鼠标事件
/*遮罩层代码 作用:通过遮罩层的方式防止表单提交次数过多 */ function MaskIt(obj){ var hoverdiv = '<div class="divMask&q ...
- static关键字作用
之前讲到final关键字的作用是每次面试的时候我必问求职者的两个问题之一,另外一个问题就是文本会写到的static.final和static一样,都是一个小问题可以看到一个人的基础是否扎实以及平时是否 ...
- java自学之路-开篇
开篇 想写一些java自学文章的心思起好久了,也在心里规划了一段时间,今天终于开始正式付于纸上.接下来要写的内容从java基础开始,一步步到正式工作用到的技术,整个体系适合java初学者自学.内容可能 ...
- 06-码蚁JavaWeb之Servlet生命周期与基本配置
学习地址:[撩课-JavaWeb系列1之基础语法-前端基础][撩课-JavaWeb系列2之XML][撩课-JavaWeb系列3之MySQL][撩课-JavaWeb系列4之JDBC][撩课-JavaWe ...
- python_tensorflow_Django实现逻辑回归
1.工程概要 2.data文件以及input_data文件准备 链接:https://pan.baidu.com/s/1EBNyNurBXWeJVyhNeVnmnA 提取码:4nnl 3.logiss ...
- Windows下多个JDK版本之间的切换
一.JDK版本切换批处理脚本 我们平时在window上做开发的时候,可能需要同时开发两个甚至多个项目,有时不同的项目对JDK的版本要求有区别,这时候我们可能会在一台电脑上安装多个版本的JDK,如下 ...