自引用

public class PictureCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int CategoryId { get; set; }
public virtual string Name { get; set; }
public virtual int? ParentCategoryId { get; set; } [ForeignKey("ParentCategoryId")]
public virtual PictureCategory ParentCategory { get; set; } public virtual List<PictureCategory> SubCategories { get; set; } public PictureCategory()
{
SubCategories = new List<PictureCategory>();
}
} 在dbcontext类下添加: public DbSet<PictureCategory> PictureCategories { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); modelBuilder.Entity<PictureCategory>()
.HasMany(p => p.SubCategories)
.WithOptional(p => p.ParentCategory); }

拆分实体到多张表

public class Product
{
public int ProductId { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string ImgUrl { get; set; }
} 在dbcontext类下添加: public DbSet<Product> Products { get; set; } public override void OnModelCreating(DbModelBuiler modelBuilder)
{
base.OnModelCreating(modelBuilder); modelBuilder.Entity<Product>()
.Map(p=>{
p.Properties(t=>new { t.ProductId, t.Description, t.Price });
p.ToTable("Product","Chapter2");
})
.Map(p=>{
p.Properties(t=>new { t.ProductId, t.ImgUrl });
p.ToTable("ProductWebInfo","Chapter2");
});
}

分拆一张表到多个实体

public class Photograph
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhotoId { get; set; } public string Title{ get; set; } public byte[] ThumbnailBits { get; set; } [ForeignKey("PhotoId")]
public virtual PhotographFullImage PhotographFullImage { get; set; }
} public class PhotographFullImage
{
[Key]
public int PhotoId { get; set; } public byte[] HighResolutionBits { get; set; }
[ForeignKey("PhotoId")]
public virtual Photograph Photograph{ get; set; }
} 在dbcontext类下添加: public DbSet<Photograph> Photographs { get; set; }
public DbSet<PhotographFullImage> PhotographFullImages { get; set; } modelBuilder.Entity<Photograph>()
.HasRequired(p => p.PhotographFullImage)
.WithRequiredPrincipal(p => p.Photograph);
modelBuilder.Entity<Photograph>().ToTable("Photograph", "Chapter2");
modelBuilder.Entity<PhotographFullImage>().ToTable("Photograph", "Chapter2");

TPT映射

[Table("Bussiness", Schema = "Chapter2")]
public class Bussiness
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BussinessId { get; set; } public string Name { get; set; } public string LicenseNumber { get; set; }
} [Table("ECommerce", Schema = "Chapter2")]
public class ECommerce : Bussiness
{
public string Url { get; set; }
} [Table("Retail", Schema = "Chapter2")]
public class Retail : Bussiness
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
} 在dbcontext类下添加: public DbSet<Bussiness> Bussinesses { get; set; } 获得子类类型时: dbContext.Bussinesses.OfType<Retail>();

TPH映射

[Table("Employee",Schema = "Chapter2")]
public abstract class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
} public class FullTimeEmployee : Employee
{
public decimal? Salary { get; set; }
} public class HourlyEmployee : Employee
{
public decimal? Wage { get; set; }
} 在dbcontext类下添加: public DbSet<Employee> Employees { get; set; } modelBuilder.Entity<Employee>()
.Map<FullTimeEmployee>(m => m.Requires("EmployeeType").HasValue(1)
.Map<HourlyEmployee>(m => m.Requires("EmployeeType").HasValue(2));

常用查询方法

1.执行非查询sql语句

db.DataBase.ExecuteSqlCommand("delete a where id=xx");

2.执行sql查询语句

db.DataBase.SqlQuery<ADto>("select * from a"); 其重载方法可以传入参数,可以执行存储过程

3.构建ado.net对象

using (var conn = new EntityConnection("name=EFRecipesEntities"))
{
Console.WriteLine("Customers...");
var cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = @"select c.Name, C.Email from EFRecipesEntities.Customers as c";
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
Console.WriteLine("{0}'s email is: {1}",
reader.GetString(0), reader.GetString(1));
}
}
}

4.查找主从复合结构关系中的拥有从表记录的主表记录

from blog in db.BlogPost
where blog.Comments.Any()
select blog

5.在查询中设置默认值

from e in context.Employees
select new { Name = e.Name, YearsWorked = e.YearsWorked ?? 0 };

6.从存储过程中返回多结果集

  using (var context = new EFRecipesEntities())
{
var cs = @"Data Source=.;Initial Catalog=EFRecipes;Integrated Security=True";
var conn = new SqlConnection(cs);
var cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Chapter3.GetBidDetails";
conn.Open();
var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
var jobs = ((IObjectContextAdapter)context).ObjectContext.Translate<Job>(reader, "Jobs",
MergeOption.AppendOnly).ToList();
reader.NextResult();
((IObjectContextAdapter)context).ObjectContext.Translate<Bid>(reader, "Bids", MergeOption.AppendOnly)
.ToList();
foreach (var job in jobs)
{
Console.WriteLine("\nJob: {0}", job.JobDetails);
foreach (var bid in job.Bids)
{
Console.WriteLine("\tBid: {0} from {1}",
bid.Amount.ToString(), bid.Bidder);
}
} Console.WriteLine("\nPress <enter> to continue...");
Console.ReadLine();
}

7.与列表值比较

 var cats = new List<string> { "Programming", "Databases" };
var books = from b in context.Books
where cats.Contains(b.Category.Name)
select b;

8.过滤关联实体

using (var context = new EFRecipesEntities())
{
// 显式禁用延迟加载
//如果打开延迟加载,所有的accidents将在我们引用worker的accidents时才加载。这将导致过虑失败
context.Configuration.LazyLoadingEnabled = false;
var query = from w in context.Workers
select new
{
Worker = w,
Accidents = w.Accidents.Where(a => a.Severity > 2)
};
// 匿名类型不会把accidents附加到workers上,
//但是通过把它们带到上下文中,实体框架会填充导航属性,
//将每一个严重事故集合accidents附加到合适的worker上。这个过程一般叫做:Entity Span。
//这是一个强大而微妙的,发生在实体框架实例化实体类型及它们之间关系的幕后的副作用
query.ToList();
var workers = query.Select(r => r.Worker);
Console.WriteLine("Workers with serious accidents...");
foreach (var worker in workers)
{
Console.WriteLine("{0} had the following accidents", worker.Name);
if (worker.Accidents.Count == 0)
Console.WriteLine("\t--None--");
foreach (var accident in worker.Accidents)
{
Console.WriteLine("\t{0}, severity: {1}",
accident.Description, accident.Severity.ToString());
}
}
}

9.应用左连接

Product与 TopSellings(热销产品)的关系为 1-0...1

from p in context.Products
join t in context.TopSellings on
//注意,我们如何将结果集投影到另一个名为'g'的序列中,
//以及应用DefaultIfEmpty方法,当g为空时用null填充
p.ProductID equals t.ProductID into g
from tps in g.DefaultIfEmpty()
orderby tps.Rating descending
select new
{
Name = p.Name,
Rating = tps.Rating == null ? 0 : tps.Rating
};

10.通过TPH派生类排序

from m in context.Media
let mediumtype = m is Article
? 1
: m is Video ? 2 : 3
orderby mediumtype
select m;

11.按日期分组

var groups = from r in context.Registrations
// 凭借内置的TruncateTime函数提取Date部分
group r by DbFunctions.TruncateTime(r.RegistrationDate)
into g
select g;

12.结果集扁平化

Associates与AssociateSalariess是 1-*的关系
var allHistory = from a in context.Associates
from ah in a.AssociateSalaries.DefaultIfEmpty()
orderby a.Name
select new
{
Name = a.Name,
Salary = (decimal?)ah.Salary,
Date = (DateTime?)ah.SalaryDate
};

13.使用多属性分组

var results = from e in context.Events
// 使用匿名类型封闭复合key State 和City
group e by new { e.State, e.City } into g
select new
{
State = g.Key.State,
City = g.Key.City,
Events = g
};

14.过滤中使用位操作

用整型来做标识位,这个整型的值分别是2的整数次幂,存入数据时用或(|)操作,查询时用与(&)操作

public enum SponsorTypes
{
None = 0,
ContributesMoney = 1,
Volunteers = 2,
IsABoardMember = 4
}; context.Patrons.Add(new Patron
{
Name = "Ryan Keyes",
//注意位操作符中的OR操作符'|'的用法
SponsorType = (int)(SponsorTypes.ContributesMoney |
SponsorTypes.IsABoardMember)
}); var sponsors = from p in context.Patrons
//注意位操作符中的AND操作符'&'的用法
where (p.SponsorType &
(int)SponsorTypes.ContributesMoney) != 0
select p;

15.多列连接(Join)

var orders = from o in context.Orders
join a in context.Accounts on
// 使用匿名类型来构造一个复合的查询表达式
new { Id = o.AccountId, City = o.ShipCity, State = o.ShipState }
equals
new { Id = a.AccountId, City = a.City, State = a.State }
select o;

Entity Framework 6 学习笔记的更多相关文章

  1. Entity Framework 6 学习笔记2 — 增、删、改、显示简单代码示例

    前言 通过 “Entity Framework 6 学习笔记1 — 介绍和安装方法”文章我相信大家对EF的安装应该没什么问题了,整体安装还是比较简单的,只需要通过Nuge搜索EF然后安装就可以了,这也 ...

  2. 【Pro ASP.NET MVC 3 Framework】.学习笔记.7.SportsStore:购物车

    3 创建购物车 每个商品旁边都要显示Add to cart按钮.点击按钮后,会显示客户已经选中的商品的摘要,包括总金额.在购物车里,用户可以点击继续购物按钮返回product目录.也可以点击Check ...

  3. 【Pro ASP.NET MVC 3 Framework】.学习笔记.5.SportsStore一个真实的程序

    我们要建造的程序不是一个浅显的例子.我们要创建一个坚固的,现实的程序,坚持使它成为最佳实践.与Web Form中拖控件不同.一开始投入MVC程序付出利息,它给我们可维护的,可扩展的,有单元测试卓越支持 ...

  4. 【Pro ASP.NET MVC 3 Framework】.学习笔记.12.ASP.NET MVC3的细节:URLs,Routing和Areas

    Adam Applied ASP.NET 4 in Context 1 介绍Routing系统 在引入MVC之前,ASP.NET假定被请求的URLs和服务器硬盘上的文件之间有着直接关系.服务器的任务是 ...

  5. 【Pro ASP.NET MVC 3 Framework】.学习笔记.11.ASP.NET MVC3的细节:概览MVC项目

    书Adam The Definitive Guide to HTML5 Adam Applied ASP.NET 4 in Context and Pro ASP.NET 4 到此为止,我们已经学了为 ...

  6. 【Pro ASP.NET MVC 3 Framework】.学习笔记.10.SportsStore:上传图片

    1 扩展数据库 打开表定义,新增两列可空 ) 2 增强领域模型 为Products类添加如下属性 publicstring ImageMimeType { get; set; } 第一个属性不会在界面 ...

  7. 【Pro ASP.NET MVC 3 Framework】.学习笔记.9.SportsStore:Securing the Administration Features

    1 设置表单身份认证 因为ASP.NET MVC基于ASP.NET平台的核心,所以我们可以使用ASP.NET Form的身份认证,这是保持用户登录轨迹通用的方法.现在介绍最基本的配置. 在Web.co ...

  8. 【Pro ASP.NET MVC 3 Framework】.学习笔记.8.SportsStore:管理

    管理功能,如何身份认证,对controller和action方法过滤安全的访问,并在用户需要时提供证书. 1 添加分类管理 方便管理的controller,有两类页面,List页面和edit页面. 1 ...

  9. 【Pro ASP.NET MVC 3 Framework】.学习笔记.6.SportsStore:导航

    在之前的章节,偶们设置了核心的基础设施,现在我们将使用基础设计添加关键特性,你将会看到投资是如何回报的.我们能够很简单很容易地添加重要的面向客户的特性.沿途,你也会看到一些MVC框架提供的附加的特性. ...

随机推荐

  1. EntityFramework - Migrations

    EntityFramework  - Migrations 對項目進行EF的數據庫升級操作.分爲開發環境與部署環境.上的操作總結. 引用: Command說明https://coding.abel.n ...

  2. 使用Echarts的五个步骤

     _liuz 2015-07-22 09:35:53 参考网址:http://echarts.baidu.com/doc/start.html 一.制作一个图表容器<div id="m ...

  3. BZOJ 3884 上帝与集合的正确用法

    Description 根据一些书上的记载,上帝的一次失败的创世经历是这样的: 第一天, 上帝创造了一个世界的基本元素,称做"元". 第二天, 上帝创造了一个新的元素,称作&quo ...

  4. GPIO模拟串口注意是事项

    GPIO模拟串口需要注意的事项如下:(程序见我的博客第一篇) 1.由于串口是异步通信,则串口发送必须满足宽度要求. (1)假设串口的波特率是9600bps(1s传输9600个bit),则传输1bit需 ...

  5. Csharp 简单操作Word模板文件

    原文:Csharp 简单操作Word模板文件 1.创建一个模板的Word文档  Doc1.dot 内容为: To: <Name> Sub:<Subject> Website i ...

  6. Request.url用法

    原文:Request.url用法 我們在開發網頁應用程式,時常需要去解析網址(Request.Url)的每個片段,進行一些判斷.例如說 "http://localhost:1897/News ...

  7. iOS cell自动换行

    // //  DynamicHeightsViewController.h //  DynamicHeights // //  Created by Matt Long on 9/22/09. //  ...

  8. struts2的action访问servlet API的三种方法

    学IT技术,就是要学习... 今天无聊看看struts2,发现struts2的action访问servlet API的三种方法: 1.Struts2提供的ActionContext类 Object g ...

  9. Apache Struts 多个开放重定向漏洞(CVE-2013-2248)

    漏洞版本: Struts < 2.3.15.1 漏洞描述: BUGTRAQ ID: 61196 CVE(CAN) ID: CVE-2013-2248 Struts2 是第二代基于Model-Vi ...

  10. 「Poetize7」Freda的访客

    描述 Description 小猫们看到蛋糕比饼干大之后,普遍认为蛋糕比饼干要好>.<.所以,如果Freda 给了第i 只小猫蛋糕且这个小猫是第一个吃到蛋糕的,那么就必须给第i+2,i+4 ...