Code First,顾名思义,要先写Code,而不是先建立数据库内容。
同样使用与上文 Database First 模式相同的例子,假设需要设计一个零售系统,我们先构建一个 Customer 类。
1 [Table("Customer", Schema = "STORE")] 2 public class Customer 3 { 4 [Key] 5 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 6 public long Id { get; set; } 7 public string Name { get; set; } 8 public string Address { get; set; } 9 public string Phone { get; set; } 10 }
通过使用TableAttribute来指定数据表名称和使用的SchemaName。
通过KeyAttribute来指定表主键,并通过DatabaseGeneratedAttribute来指定该主键为自增字段。
构建访问上下文,
1 public class RetailEntities : DbContext 2 { 3 static RetailEntities() 4 { 5 //Database.SetInitializer<RetailEntities>(new CreateDatabaseIfNotExists<RetailEntities>()); 6 //Database.SetInitializer<RetailEntities>(new DropCreateDatabaseAlways<RetailEntities>()); 7 //Database.SetInitializer<RetailEntities>(new DropCreateDatabaseIfModelChanges<RetailEntities>()); 8 Database.SetInitializer<RetailEntities>(null); 9 } 10 11 public RetailEntities() 12 : base("Name=RetailEntities") 13 { 14 } 15 16 public DbSet<Customer> Customers { get; set; } 17 }
其中包含了几种数据库初始化选项,
- CreateDatabaseIfNotExists 如果数据库不存在则创建。
- DropCreateDatabaseAlways 总是先删除已有数据库并创建新的。
- DropCreateDatabaseIfModelChanges 判断如果模型有修改在重建数据库。
同时需要在配置文件中指定数据库访问字符串,
<connectionStrings> <add name="RetailEntities" connectionString="Data Source=localhost\DENNIS;Initial Catalog=RETAIL;Integrated Security=True;MultipleActiveResultSets=True;Application Name=WhenEntityFrameworkMeetUnity;" providerName="System.Data.SqlClient" /> </connectionStrings>
这样,就可以构建同样的增删改查功能了。参考上文DatabaseFirst中定义个ICustomerRepository接口。
1 public void InsertCustomer(DomainModels.Customer customer) 2 { 3 using (RetailEntities context = new RetailEntities()) 4 { 5 Customer entity = Mapper.Map<DomainModels.Customer, Customer>(customer); 6 context.Customers.Add(entity); 7 context.SaveChanges(); 8 9 customer.Id = entity.Id; 10 } 11 } 12 13 public void UpdateCustomer(DomainModels.Customer customer) 14 { 15 using (RetailEntities context = new RetailEntities()) 16 { 17 Customer entity = context.Customers.AsQueryable().Single(c => c.Id == customer.Id); 18 19 entity.Name = customer.Name; 20 entity.Address = customer.Address; 21 entity.Phone = customer.Phone; 22 23 context.SaveChanges(); 24 } 25 }
具体使用,
1 ICustomerRepository customerRepository = new CustomerRepository(); 2 3 // =============== 增 =============== 4 Console.ForegroundColor = ConsoleColor.DarkRed; 5 6 DomainModels.Customer customer1 = new DomainModels.Customer() 7 { 8 Name = "Dennis Gao", 9 Address = "Beijing", 10 Phone = "18888888888", 11 }; 12 customerRepository.InsertCustomer(customer1); 13 Console.WriteLine(customer1);
完整代码和索引
EntityFramework用法探索系列
- (一)DatabaseFirst
- (二)CodeFirst
- (三)CodeFirst流畅API
- (四)Repository和UnitOfWork
- (五)引入Unity
- (六)静态Repository
- (七)线程安全实践
- (八)事务处理
本文转自匠心十年博客园博客,原文链接:http://www.cnblogs.com/gaochundong/archive/2013/06/06/entityframework_usage_code_first.html,如需转载请自行联系原作者