前言

EF已经发布很久了,也有越来越多的人在使用EF。如果你已经能够非常熟练的使用EF的功能,那么就不需要看了。本文意在将自己使用EF的方式记录下来备忘,也是为了给刚刚入门的同学一些指导。看完此文,你应该就学会以CodeFirst的方式操作数据库了。

本文主要内容

  • CodeFirst生成数据库的流程
  • 初始化配置
  • 数据库实体构造技巧
  • 主外键设置
  • decimal精度修改

项目框架搭建

本文所使用的开发工具是vs2015(EF6.1.3)

第一步:新建一个空白项目

EF使用CodeFirst方式生成数据库&技巧经验

第二步:引用EntityFramework

EF使用CodeFirst方式生成数据库&技巧经验

EF使用CodeFirst方式生成数据库&技巧经验

 

DbContext的初始化配置

 DbContext作为操作数据库的网关,十分重要。我们需要对它进行一些类的初始化操作,例如:解决团队开发中,多人迁移数据库造成的修改覆盖问题。

代码如下:

EF使用CodeFirst方式生成数据库&技巧经验
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace EFDemo.Core.EF
{
    /// <summary>
    /// EF访问数据库的接口   
    /// </summary>
    public class MyDbContext : System.Data.Entity.DbContext
    {        
        public MyDbContext()
            : base("EFDemo")
        {
            //解决团队开发中,多人迁移数据库造成的修改覆盖问题。
            Database.SetInitializer<MyDbContext>(null);
            //base.Configuration.AutoDetectChangesEnabled = false;
            ////关闭EF6.x 默认自动生成null判断语句
            //base.Configuration.UseDatabaseNullSemantics = true;           
        }    
        public MyDbContext(System.Data.Common.DbConnection oConnection)
            : base(oConnection, true)
        {
            this.Configuration.LazyLoadingEnabled = true;         
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //表名不用复数形式
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //移除一对多的级联删除约定,想要级联删除可以在 EntityTypeConfiguration<TEntity>的实现类中进行控制
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            //多对多启用级联删除约定,不想级联删除可以在删除前判断关联的数据进行拦截
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();          

            base.OnModelCreating(modelBuilder);
        }
        //将实体对象写在这里,就可以生成对应的数据。 如下:
        //public DbSet<Demo> Demo { get; set; }


  

    }


}
EF使用CodeFirst方式生成数据库&技巧经验

项目位置:

EF使用CodeFirst方式生成数据库&技巧经验

Migrations下Configuration类的初始化配置

 Configuration类的初始化配置十分重要,我们需要通过配置解决一系列迁移问题。例如:允许自动迁移,自动迁移默认情况下不扔掉列在我们的数据库中的表。如果我们不希望这样的行为,我们可以告诉迁移明确允许数据丢失的配置类的AutomaticMigrationDataLossAllowed属性设置为true。

代码如下:

EF使用CodeFirst方式生成数据库&技巧经验
namespace EFDemo.Core.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<EFDemo.Core.EF.MyDbContext>
    {
        public Configuration()
        {
            //允许自动迁移
            //不然会报错Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.You can use the Add-Migration command to write the pending model changes to a code-based migration.

            //允许自动迁移
            AutomaticMigrationsEnabled = true;
            //自动迁移默认情况下不扔掉列在我们的数据库中的表。如果我们不希望这样的行为,我们可以告诉迁移明确允许数据丢失的配置类的AutomaticMigrationDataLossAllowed属性设置为true。
            AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(EF.MyDbContext context)
        {
            
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}
EF使用CodeFirst方式生成数据库&技巧经验

项目位置:

EF使用CodeFirst方式生成数据库&技巧经验

数据库对应实体对象的定义

 CodeFirst模式需要我们先定义实体,然后通过实体生成数据。

通常我们设计数据库表时,每个表都有(ID,是否删除,备注,添加人,添加时间,修改人,修改时间)等字段。我们可以用基类处理

基类实体:

EF使用CodeFirst方式生成数据库&技巧经验
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFDemo.Core.Entity
{
    public class BaseEntity
    {

    }
    [Serializable]
    public class BaseEntity<TKey> : BaseEntity
    {
        public BaseEntity()
        {
            this.AddTime = DateTime.Now;
        }

        [Key]
        [Display(Name = "编号")]
        public TKey ID { get; set; }
        [Display(Name = "排序")]
        [Required(ErrorMessage = "{0}是必填项"), Range(0, int.MaxValue, ErrorMessage = "{0}的范围是{1}到{2}")]
        [DefaultValue(0)]
        public int Sort { get; set; }
        [Display(Name = "备注")]
        [MaxLength(256, ErrorMessage = "{0}最大长度{1}")]
        public string Remark { get; set; }
        [Display(Name = "是否删除")]
        [Required]
        public bool Deleted { get; set; }
        public int AddUser { get; set; }
        [Display(Name = "添加时间")]
        [DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:yyyy-MM-dd HH mm}", HtmlEncode = false, NullDisplayText = "数据无效")]
        public DateTime AddTime { get; set; }
        public int ModUser { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:yyyy-MM-dd  HH mm}", HtmlEncode = false, NullDisplayText = "数据无效")]
        public DateTime? ModTime { get; set; }

    }
  

}
EF使用CodeFirst方式生成数据库&技巧经验

相关文章:

  • 2021-09-04
  • 2021-06-09
  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-13
  • 2021-09-12
  • 2021-07-30
  • 2021-05-17
  • 2022-12-23
  • 2021-06-22
相关资源
相似解决方案