使用ef core 的简单配置


注:下面内容摘自https://blog.csdn.net/qq_25086397/article/details/88895763和https://blog.csdn.net/weixin_43537631/article/details/110678496博客,如有学习,请自行跳转

以下仅为自行记录笔记。

1.前期准备插件

  Microsoft.EntityFrameworkCore.SqlServer(放在模型-数据库实体项目)

  Microsoft.EntityFrameworkCore.Tools(放在模型-数据库实体项目)

  Microsoft.EntityFrameworkCore(放在主项目)

  Microsoft.EntityFrameworkCore.Design(放在主项目)

2.使用efcore相关配置

namespace EFCModels
{
    /// 
    /// 数据库模型
    /// 
    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string PWD { get; set; }
    }
}

 

using EFCModels;
using Microsoft.EntityFrameworkCore;

namespace EFCModel
{
    /// 
    /// 建立上下文
    /// 
    public class EFMContext:DbContext
    {
        public EFMContext(DbContextOptions options) : base(options) { }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }
        /// 
        /// 数据库实体
        /// 
        public DbSet Users { get; set; }
    }
}

string connection = @"server=NAMEJR-PC;database=EFCoreDemo;uid=*******;pwd=*******";//windows身份验证(添加数据库路径)
            services.AddDbContext(options => options.UseSqlServer(connection, c => c.MigrationsAssembly("EFCoreUse")));  // 配置当前项目关联实体和数据库

打开控制台准备进行生成数据库

生成对应的数据库信息

 3.拓展

   3.1关于数据库字段的限制,详细可查看,此处仅做笔记记录

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFCModels
{
    [Table("User")]  // 设置表名
    /// 
    /// 数据库模型
    /// 
    public class User
    {
        // 可以写成[Key,Required]
        [Key]  // 设置主键
        [Required]  // 必填字段
        [Column("id",Order =0,TypeName ="int(11)")]  //id表示数据库的名称,Order表示出现的顺序,TypeName类型
        public int ID { get; set; }
        [MaxLength(20),MinLength(0)]  // 设置最大最小长度
        public string Name { get; set; }
        [NotMapped]  // 单独的数据(不会映射到数据库中去,获取的时候也不是从数据库中获取)
        public string PWD { get; set; } = "******";
    }
}

//