Entity Framework实体拆分

一、概念

实体拆分:一个实体拆分成多个表,如Product实体,可以拆分成Product和ProductWebInfo两个表,Product表用于存储商品的字符类信息,ProductWebInfo用于存储商品的图片信息,两张表通过SKU进行关联。

1、Product实体类结构:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.ComponentModel.DataAnnotations.Schema;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace 实体拆分.Model
10 {
11     public class Product
12     {
13         [Key]
14         [DatabaseGenerated(DatabaseGeneratedOption.None)] //设置主键需要自己填充
15         public int SKU { get; set; }  
16         public string Description { get; set; }
17 
18         public decimal Price { get; set; }
19 
20         public string ImageURL { get; set; }
21     }
22 }

 2、数据实体类结构:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Entity;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using 实体拆分.Model;
 8 
 9 namespace 实体拆分.DatabaseContext
10 {
11     public class EFDbContext :DbContext
12     {
13         public EFDbContext()
14             : base("name=Default")
15         { }
16 
17 
18         public DbSet<Product> Products { get; set; }
19 
20         protected override void OnModelCreating(DbModelBuilder modelBuilder)
21         {
22             modelBuilder.Entity<Product>().Map(p =>
23             {
24                 p.Properties(m => new { m.SKU, m.Price, m.Description });
25                 p.ToTable("Product");
26             })
27             .Map(p =>
28             {
29                 p.Properties(m => new { m.SKU, m.ImageURL });
30                 p.ToTable("ProductWebInfo");
31             });
32 
33 
34             base.OnModelCreating(modelBuilder);
35         }
36     }
37 }

 3、使用数据迁移生成数据库,生成后的表结构如下图所示:

4、测试数据:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using 实体拆分.DatabaseContext;
 7 
 8 namespace 实体拆分
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             using (var context = new EFDbContext())
15             {
16                 context.Products.Add(new Model.Product() {
17                     SKU=293,
18                     Description="C#高级编程(第10版)",
19                     Price=299 ,
20                     ImageURL="http://image.baidu.com/1.jpg"                    
21                 });
22                 // 保存
23                 context.SaveChanges();
24             }
25 
26             Console.WriteLine("创建成功");
27             Console.ReadKey();
28         }
29     }
30 }

 5、运行程序,查询数据库结果

总结将实体拆分成多表的步骤:

1、在工程中创建一个新类继承自DbContext类。
2、创建Product的POCO类。
3、在新创建的DbContext子类中添加属性:DbSet<Product>。
4、重写DbContext类的OnModelCreating()方法。

代码地址:https://files.cnblogs.com/files/dotnet261010/%E5%AE%9E%E4%BD%93%E6%8B%86%E5%88%86.rar。

posted @ 2017-12-08 22:10  .NET开发菜鸟  阅读(399)  评论(0编辑  收藏  举报