Fluent API实现概念模型和存储模型之间的映射

1.模型类

    public class Blog
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string BloggerName { get; set; }
        public string Test { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
    }
博客
    public class Post
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public int FKBlogId { get; set; }
        public Blog Blog { get; set; }
        public ICollection<Comment> Comments { get; set; }
    }
帖子
    public class Comment
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public DateTime CreateTime { get; set; }
        public ICollection<Post> Posts { get; set; }
    }
评论

2.实现概念模型和存储模型之间的映射

public class BaseDbContext:DbContext
    {
        private static readonly string Connection = ConfigurationManager.AppSettings["DbConnection"].ToString();
        public BaseDbContext()
            : base(Connection)
        {
            this.Database.CreateIfNotExists();
        }
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            //1、给表Blog设置主键
            modelBuilder.Entity<Blog>().HasKey(c => c.Id);
            //2、概念实体映射到存储实体的实体名改变
            modelBuilder.Entity<Blog>().ToTable("Blog", "dbo");
            //3、给存储模型设置别名,EF的强大之处在于概念模型和存储模型对应的字段的名称可以不一样,但它还能认识,我估计是以键对值的方式在存储别名
            modelBuilder.Entity<Blog>().Property(t => t.Test).HasColumnName("TestName");

            //4、设置实体之间一对多的关系 同时指定了Blog的外键:FK_BlogId
            modelBuilder.Entity<Post>().HasRequired(p => p.Blog)
                .WithMany(b => b.Posts)
                .HasForeignKey(p => p.FKBlogId);

            //5、设置实体之间多对多的关系 实现多对多的关系是建立一张两表对应的关系表
            modelBuilder.Entity<Post>().HasMany(p => p.Comments)
                .WithMany(c => c.Posts).Map(mc =>
                {
                    mc.ToTable("ComtentToPost");
                    mc.MapRightKey("CommentId");
                    mc.MapLeftKey("PostId");
                });

            //6、设置存储实体的字段为非空类型
            modelBuilder.Entity<Blog>().Property(c => c.Title).IsRequired();

            //7、设置字段长度
            modelBuilder.Entity<Blog>().Property(c => c.Title).HasMaxLength(12);

            //8、设置字段类型
            modelBuilder.Entity<Blog>().Property(c => c.BloggerName).HasColumnType("varchar");
        }
    }
DbContext
原文地址:https://www.cnblogs.com/liandy0906/p/8471606.html