EF之表拆分

表拆分:将一张表拆分成多个实体。

例:Code First模式下将User表拆分成UserUserInfo实体类。

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new DemoContext())
            {
                User user = new User { UserName = "Tony", Password = "3.1415926" };
                db.Users.Add(user);
                UserInfo userInfo = new UserInfo { RealName = "吴先森", Age = 25, Address = "BJ" };
                db.UserInfos.Add(userInfo);
                db.SaveChanges();

                IEnumerable users = db.Users.AsEnumerable();
                foreach (var u in users)
                {
                    Console.WriteLine("UserName:{0}, Password:{1}, RealName:{2}.", u.UserName, u.Password, u.UserInfo.RealName);
                }
            }

            Console.ReadKey();
        }
    }

    //DbContent
    public class DemoContext : DbContext
    {
        public DemoContext()
            : base("name=DemoContext")
        {
            
        }

        public DbSet Users { get; set; }
        public DbSet UserInfos { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //many entities to one table
            modelBuilder.Entity()
                .HasKey(t => t.UserId);

            modelBuilder.Entity()
                .HasKey(t => t.UserId);

            modelBuilder.Entity()
                .HasRequired(t => t.User)
                .WithRequiredPrincipal(t => t.UserInfo);

            modelBuilder.Entity().ToTable("User");
            modelBuilder.Entity().ToTable("User");

            base.OnModelCreating(modelBuilder);
        }
    }

    //Entities
    public class User
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        public virtual UserInfo UserInfo { get; set; }
    }

    public class UserInfo
    {
        public int UserId { get; set; }
        public string RealName { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }


        public virtual User User { get; set; }
    }
}


你可能感兴趣的:(Entity,Framework)