.Net EF Core IEntityTypeConfiguration之CodeFirst实现(SqlServer)

针对.net core EF框架下的CodeFirst实现(Webapi项目)

1、配置文件appsettings.json配置数据库连接

 "ConnectionStrings": {
    "SOADBContext": "Data Source=.;Initial Catalog=RextecSOA;User=sa;Password=123456" //sqlserver
  }

2、startup 数据库连接

services.AddDbContext<SOADbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SOADBContext")));

3、IEntityTypeConfiguration 实现数据表映射

创建.net core 类库 Rextec.SOA.Configuring

实现代码:

 数据表通用字段映射(基础映射类)

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Rextec.SOA.Repository;

namespace Rextec.SOA.Configuring
{
    /// <summary>
    /// 通用字段映射
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseConfiguring<T> : IEntityTypeConfiguration<T> where T : BaseModel
    {
        public virtual void Configure(EntityTypeBuilder<T> builder)
        {
            builder.HasKey(x => x.ID);
            builder.Property(x => x.CreateUserID).HasMaxLength(50).IsRequired();
            builder.Property(x => x.CreateUserName).HasMaxLength(50);
            builder.Property(x => x.CreateTime).HasColumnType("datetime");
            builder.Property(x => x.ModifyUserID).HasMaxLength(50);
            builder.Property(x => x.ModifyUserName).HasMaxLength(50);
            builder.Property(x => x.ModifyTime).HasColumnType("datetime");
        }
    }
}

以用户表映射代码

using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Rextec.SOA.Repository;

namespace Rextec.SOA.Configuring
{
    /// <summary>
    /// 人员表映射
    /// </summary>
    public  class UserInfoConfiguring:BaseConfiguring<UserInfo>
    {
        public override void Configure(EntityTypeBuilder<UserInfo> builder)
        {
            builder.Property(x => x.UserName).HasMaxLength(50);
            builder.Property(x => x.LoginAccount).HasMaxLength(50);
            builder.Property(x => x.LoginPassword).HasMaxLength(50);
            builder.Property(x => x.Tel).HasMaxLength(50);
            builder.Property(x => x.Email).HasMaxLength(50);
            builder.Property(x => x.Sex).HasMaxLength(50);
            builder.Property(x => x.IsEnable).HasMaxLength(1);
            builder.Property(x => x.DataLimit).HasMaxLength(1);
            builder.Property(x => x.IsAdmin).HasMaxLength(1);
        }
    }
}

通用字段实体类对象代码

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Rextec.SOA.Repository
{
    /// <summary>
    /// 通用字段实体类
    /// </summary>
    public abstract class BaseModel
    {
        /// <summary>
        /// 主键
        /// </summary>
        [Key,StringLength(50)]
        public string ID { get; set; } = Guid.NewGuid().ToString();
        /// <summary>
        /// 创建人
        /// </summary>
        [Required,StringLength(50)]
        public string CreateUserID { get; set; }
        /// <summary>
        /// 创建人姓名
        /// </summary>
        public string CreateUserName { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; } = DateTime.Now;
        /// <summary>
        /// 修改人ID
        /// </summary>
        public string ModifyUserID { get; set; }
        /// <summary>
        /// 修改人姓名
        /// </summary>
        public string ModifyUserName { get; set; }
        /// <summary>
        /// 修改日期
        /// </summary>
        public DateTime? ModifyTime { get; set; }
    }
}

人员实体类对象代码

using System.ComponentModel.DataAnnotations.Schema;

namespace Rextec.SOA.Repository
{
    /// <summary>
    /// 用户信息表
    /// </summary>
    [Table("UserInfo")]
    public class UserInfo:BaseModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 登录名
        /// </summary>
        public string LoginAccount { get; set; }
        /// <summary>
        /// 登录密码
        /// </summary>
        public string LoginPassword { get; set; }
        /// <summary>
        /// 联系电话
        /// </summary>
        public string Tel { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }
        /// <summary>
        /// 性别 0:男 1:女
        /// </summary>
        public string Sex { get; set; }
        /// <summary>
        /// 性别描述
        /// </summary>
        [NotMapped]
        public string SexDescrib { get { return Sex == "0" ? "男" : (Sex == "1" ? "女" : ""); } }
        /// <summary>
        /// 是否可用 0 否 1:是 默认可用
        /// </summary>
        public int IsEnable { get; set; } = 1;
        /// <summary>
        /// 用户数据权限 1:本人 2:不限  
        /// </summary>
        public int DataLimit { get; set; }
        /// <summary>
        /// 是否管理员 0:否 1:是 默认否
        /// </summary>
        public int IsAdmin { get; set; }
    }
}

4、数据库上下文代码

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Rextec.SOA.Repository
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    public class SOADbContext:DbContext
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="options"></param>
        public SOADbContext(DbContextOptions<SOADbContext> options):base(options)
        {
            //Database.Migrate();//如果数据库不存在,则创建数据库(migrations创建)
            Database.EnsureCreated();//如果数据库不存在则创建则创建数据库
        }
        #region dbSet
        public virtual DbSet<UserInfo> UserInfos { get; set; }
        #endregion

        /// <summary>
        /// 数据库表初始化
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            try
            {
                //modelBuilder.ApplyConfiguration(new UserInfoConfiguring());//单个文件映射
                //var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
                string path = AppDomain.CurrentDomain.BaseDirectory;
                var files = Directory.GetFiles(path, "Rextec.SOA.Configuring.dll");
                if (files.Length > 0)
                {
                    var typesToRegister = Assembly.LoadFile(files[0]).GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
                    foreach (var type in typesToRegister)
                    {
                        if (!type.FullName.Contains("BaseConfiguring"))
                        {
                            dynamic configurationInstance = Activator.CreateInstance(type);
                            modelBuilder.ApplyConfiguration(configurationInstance);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}

亲测:

使用Postman 调用接口;数据库不存在时,会自动创建数据库

自动创建的数据表如下

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的仓储系统数据库设计,使用 .NET EF Core Code First: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } public int WarehouseId { get; set; } public Warehouse Warehouse { get; set; } } public class Warehouse { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public List<Product> Products { get; set; } } public class Order { public int Id { get; set; } public DateTime OrderDate { get; set; } public int ProductId { get; set; } public Product Product { get; set; } public int Quantity { get; set; } public decimal TotalPrice { get; set; } } public class WarehouseContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Warehouse> Warehouses { get; set; } public DbSet<Order> Orders { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=WarehouseDb;Trusted_Connection=True;"); } } ``` 上述代码定义了三个实体类:Product、Warehouse 和 Order,它们分别表示产品、仓库和订单。每个产品都属于一个仓库,一个仓库可以包含多个产品。订单中包含了要购买的产品和数量以及总价。DbContext 包含了三个 DbSet 属性,分别对应这三个实体类的数据库表。在 OnConfiguring 方法中,使用 UseSqlServer 方法指定了数据库连接字符串。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值