【读书笔记】Programming Entity Framework CodeFirst -- 初步认识
以下是书《Programming Entity Framework Code First》的学习整理,主要是一个整体梳理。
一、模型属性映射约定
class AnimalType
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
[Table("Species")]
class AnimalType
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AnimalType>().ToTable("Animal");
modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
}
public class DestinationConfiguration :
EntityTypeConfiguration<Destination>
{
public DestinationConfiguration()
{
Property(d => d.Name).IsRequired();
Property(d => d.Description).HasMaxLength();
Property(d => d.Photo).HasColumnType("image");
}
}
public class LodgingConfiguration :
EntityTypeConfiguration<Lodging>
{
public LodgingConfiguration()
{
Property(l => l.Name).IsRequired().HasMaxLength();
}
}
然后再OnModelCreating中加进去,这个和modelBuilder.Entity<AnimalType>() 是同样的效果,modelBuilder.Entity<AnimalType>()会创建一个EntityTypeConfiguration。所以本质上他们是一样的代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationConfiguration());
modelBuilder.Configurations.Add(new LodgingConfiguration());
}
public class VetContext:DbContext
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; } public VetContext() : base("DefaultConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<VetContext, Configuration<VetContext>>());
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AnimalType>().ToTable("Animal");
modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
} } internal sealed class Configuration<TContext> : DbMigrationsConfiguration<TContext> where TContext : DbContext
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
namespace Model
{
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
}
namespace Model
{
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
}
namespace DataAccess
{
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
}
运行主程序:
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using (var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
static void Main()
{
InsertDestination();
}
我们在SQL Server资源管理器中可以找到这个数据库(书中说,他会自动早本机SQL Server Express中创建数据库,但是我安装的是Sql Server 2008 R2,在2008中没有找到新生成的数据库)。
而这个数据库的位置是在用户文件夹下面。右键点击ConsoleEf.BreakAwayContext 选择属性。
EF会自动的在数据表中创建主外键,并根据模型的属性的不同类型创建了不同的字段。我们再可以加一些属性约定,来限制数据库中字段的大小(注意图中的nvarchar(max)...)。修改一下Destination。
public class Destination
{
public int DestinationId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
[MaxLength()]
public string Description { get; set; }
[Column(TypeName="image")]
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
模型改变在默认状态下回触发异常,Codefirst 有几种初始化的方法。CreateDatabaseIfNotExists ,DropCreateDatabaseIfModelchanges。我们选用模型改变时删除再重建数据库。
static void Main(string[] args)
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<BreakAwayContext>());
InsertDestination();
}
再次运行,数据库已经发生改变(第一次运行出现错误,提示数据库正在使用无法删除,我在进程中删除了sqlserver.exe运行才正常),但之前的数据已经不存在了,还是数据迁移的方法最好了,EF应该把这个设置成默认功能。
【读书笔记】Programming Entity Framework CodeFirst -- 初步认识的更多相关文章
- Programming Entity Framework CodeFirst -- 约定和属性配置
以下是EF中Data Annotation和 Fluenlt API的不同属性约定的对照. Length Data Annotation MinLength(nn) MaxLength(nn) ...
- 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...
- ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)
ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...
- 第二篇:Entity Framework CodeFirst & Model 映射
前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现 ...
- Programming Entity Framework 翻译(2)-目录2-章节
How This Book Is Organized 本书组织结构 Programming Entity Framework, Second Edition, focuses on two ways ...
- Programming Entity Framework 翻译
刚开始接触.net,c#语法应该说还没掌握好.学习实践的旅程就从linq和EF开始吧.感觉相比之前的开发方式,linq和EF方便好多. linq入门用了好久,因为c#不行,补习了2.0的泛型,3.0和 ...
- Entity Framework CodeFirst数据迁移
前言 紧接着前面一篇博文Entity Framework CodeFirst尝试. 我们知道无论是“Database First”还是“Model First”当模型发生改变了都可以通过Visual ...
- [Programming Entity Framework] 第3章 查询实体数据模型(EDM)(一)
http://www.cnblogs.com/sansi/archive/2012/10/18/2729337.html Programming Entity Framework 第二版翻译索引 你可 ...
- entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败
警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...
随机推荐
- 20151208Study
20151208-----------------------------------------------------* Her main interest now is raising her ...
- python操作系统环境变量
获取整个系统变量的方法是os.environ,这是一个os的class类型,使用的时候可以转换为字典类型 environ_value = dict(os.environ) 这样就可以看所有的key,e ...
- CentOS系统下安装配置ftp服务
安装配置步骤: rpm -ivh /opt/bak/vsftpd-2.2.2-11.el6.x86_64.rpm --本地安装vsftpd ll /etc/vsftpd/ --查看vsftpd的配置 ...
- AspNetPager 免费分页控件7.5.1版发布!
AspNetPager 免费分页控件7.5.1版发布,本次升级主要内容有: 修正了ShowDisabledButtons为false时html闭合标签丢失的bug:改为从System.Web.UI.W ...
- 自己对Extjs的Xtemplate的忽略
之前学习extjs Xtmeplate受一些书籍的误导,说Xtemplate不支持else ,今天仔细看了官网的示例,才恍然大悟,卧槽!不仅支持if-elseif-else结构 连switch都能够支 ...
- Html5应用程序缓存ApplicationCache
应用缓存机制可以参考http://www.w3school.com.cn/html5/html_5_app_cache.asp,不再赘述.利用此机制,html5游戏可以实现和native app类似的 ...
- Spring overview
引子 接触Java很多年了,各种framework,却从未系统的去了解过.最近突然想清楚一件事,就是当下的目标——Focus on Java-based RESTful WS & JS.而之于 ...
- c# GridView有关RowClick事件,可单击显示选中的row
//当前选定行 int i = this.gridView1.FocusedRowHandle; //选中行,列名为name的值 gridView1.GetRowCellDisplayText(i, ...
- BZOJ2933: [Poi1999]地图
Description 一个人口统计办公室要绘制一张地图.由于技术的原因只能使用少量的颜色.两个有相同或相近人口的区域在地图应用相同的颜色.例如一种颜色k,则A(k) 是相应的数,则有: 在用颜色 ...
- 使用extjs6官方模板admin-dashboard
1.生成项目: sencha generate app -s templates/admin-dashboard/ Dashboard ../my-folder 2.修改app.json的output ...