【读书笔记】Programming Entity Framework CodeFirst -- 初步认识
2015-03-04 10:05 stoneniqiu 阅读(554) 评论(0) 编辑 收藏 举报以下是书《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(500); Property(d => d.Photo).HasColumnType("image"); } } public class LodgingConfiguration : EntityTypeConfiguration<Lodging> { public LodgingConfiguration() { Property(l => l.Name).IsRequired().HasMaxLength(200); } }
然后再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(500)] 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应该把这个设置成默认功能。
书山有路群:452450927
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义