欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Entity?Framework實體拆分多個表

 更新時間:2022年03月07日 11:05:42   作者:.NET開發(fā)菜鳥  
這篇文章介紹了Entity?Framework實體拆分多個表的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、概念

實體拆分:一個實體拆分成多個表,如Product實體,可以拆分成Product和ProductWebInfo兩個表,Product表用于存儲商品的字符類信息,ProductWebInfo用于存儲商品的圖片信息,兩張表通過SKU進行關聯(lián)。

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、數(shù)據(jù)實體類結構:

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、使用數(shù)據(jù)遷移生成數(shù)據(jù)庫,生成后的表結構如下圖所示:

4、測試數(shù)據(jù):

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("創(chuàng)建成功");
            Console.ReadKey();
        }
    }
}

 5、運行程序,查詢數(shù)據(jù)庫結果

總結

將實體拆分成多表的步驟:

1、在工程中創(chuàng)建一個新類繼承自DbContext類。
2、創(chuàng)建Product的POCO類。
3、在新創(chuàng)建的DbContext子類中添加屬性:DbSet<Product>。
4、重寫DbContext類的OnModelCreating()方法。

點此下載示例代碼

到此這篇關于Entity Framework實體拆分多個表的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論