EntityFramework用法探索(三)CodeFirst流暢API

來源:互聯網
上載者:User

Code First Fluent API,使用流暢API來定義模型映射。

同樣使用與上文 Database First 模式相同的例子,假設需要設計一個零售系統,我們先構建一個 Customer 類。

1   public class Customer2   {3     public long Id { get; set; }4     public string Name { get; set; }5     public string Address { get; set; }6     public string Phone { get; set; }7   }

這次沒有使用屬性來指定對應表名稱、主鍵等。

使用代碼建立影射,

 1   public class CustomerMap : EntityTypeConfiguration<Customer> 2   { 3     public CustomerMap() 4     { 5       // Primary Key 6       this.HasKey(t => t.Id); 7  8       // Properties 9       this.Property(t => t.Name)10           .IsRequired()11           .HasMaxLength(256);12 13       this.Property(t => t.Phone)14           .IsRequired()15           .HasMaxLength(256);16 17       // Table & Column Mappings18       this.ToTable("Customer", "STORE");19       this.Property(t => t.Id).HasColumnName("Id");20       this.Property(t => t.Name).HasColumnName("Name");21       this.Property(t => t.Address).HasColumnName("Address");22       this.Property(t => t.Phone).HasColumnName("Phone");23 24       // Relationships25       //this.HasRequired(t => t.Status)26       //    .WithMany(t => t.CustomerStatus)27       //    .HasForeignKey(d => d.Status);28     }29   }

在內容物件中覆寫OnModelCreating方法來添加影射配置,

 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 18     protected override void OnModelCreating(DbModelBuilder modelBuilder)19     {20       modelBuilder.Configurations.Add(new CustomerMap());21     }22   }

ICustomerRepository介面和實現依然類似,

 1     public void InsertCustomer(DomainModels.Customer customer) 2     { 3       using (RETAILContext context = new RETAILContext()) 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 (RETAILContext context = new RETAILContext())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);

當然,你可能覺得手工寫影射代碼還是比較繁瑣,如果已有部分資料表結構,希望反向產生代碼,可使用工具 Entity Framework Power Tools 來產生。

Entity Framework Power Tools 拯救程式員啊。

完整代碼和索引

EntityFramework用法探索系列

  • (一)DatabaseFirst
  • (二)CodeFirst
  • (三)CodeFirst流暢API
  • (四)Repository和UnitOfWork
  • (五)引入Unity
  • (六)靜態Repository
  • (七)安全執行緒實踐
  • (八)交易處理

完整代碼下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.