Entity Framework实体拆分

一、概念

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

1、Product实体类结构:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 实体拆分.Model
{
    public class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)] //设置主键需要自己填充
        public int SKU { get; set; }  
        public string Description { get; set; }

        public decimal Price { get; set; }

        public string ImageURL { get; set; }
    }
}

 2、数据实体类结构:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 实体拆分.Model;

namespace 实体拆分.DatabaseContext
{
    public class EFDbContext :DbContext
    {
        public EFDbContext()
            : base("name=Default")
        { }


        public DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().Map(p =>
            {
                p.Properties(m => new { m.SKU, m.Price, m.Description });
                p.ToTable("Product");
            })
            .Map(p =>
            {
                p.Properties(m => new { m.SKU, m.ImageURL });
                p.ToTable("ProductWebInfo");
            });


            base.OnModelCreating(modelBuilder);
        }
    }
}

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

4、测试数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 实体拆分.DatabaseContext;

namespace 实体拆分
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new EFDbContext())
            {
                context.Products.Add(new Model.Product() {
                    SKU=293,
                    Description="C#高级编程(第10版)",
                    Price=299 ,
                    ImageURL="http://image.baidu.com/1.jpg"                    
                });
                // 保存
                context.SaveChanges();
            }

            Console.WriteLine("创建成功");
            Console.ReadKey();
        }
    }
}

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

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

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

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值