赞
踩
- using System;
- using System.Collections.Generic;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Metadata;
-
- namespace Student.Manage.Api.Models
- {
- /// <summary>
- /// 添加Nuget包:
- /// Microsoft.EntityframeworkCore.Core
- /// Microsoft.EntityframeworkCore.SqlServer
- /// Microsoft.EntityframeworkCore.Tools
- /// Microsoft.EntityframeworkCore.Abstractions
- /// Microsoft.EntityframeworkCore.Relational
- /// </summary>
- public partial class TestDBContext : DbContext
- {
- public TestDBContext()
- {
- }
-
- public TestDBContext(DbContextOptions<TestDBContext> options)
- : base(options)
- {
- }
- /// <summary>
- /// Tb_Student测试实体(与数据库表结构设计保持一致)
- /// </summary>
- public virtual DbSet<Tb_Student> TbStudents { get; set; } = null!;
- /// <summary>
- /// 与数据库建立连接函数
- /// </summary>
- /// <param name="optionsBuilder"></param>
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- #region 与sqlserver数据库建立连接两种方式
- //第一种
- //optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=TestDB;Integrated Security=True;Trust Server Certificate=True");
- //第二种(在配置文件中设置数据库连接字符串)
- //"ConnectionStrings": {
- // "DbDefaultString": "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;Trust Server Certificate=True"
- //}
- optionsBuilder.UseSqlServer("name=ConnectionStrings:DbDefaultString");
- //第三种()
- //base.OnConfiguring(optionsBuilder);
- #endregion
- }
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Tb_Student>(entity =>
- {
- entity.ToTable("tb_Student");
-
- entity.Property(e => e.Id)
- .ValueGeneratedNever()
- .HasColumnName("id");
-
- entity.Property(e => e.StuAge).HasColumnName("stu_age");
-
- entity.Property(e => e.StuGender)
- .HasMaxLength(10)
- .HasColumnName("stu_gender")
- .IsFixedLength();
-
- entity.Property(e => e.StuGrade)
- .HasMaxLength(50)
- .HasColumnName("stu_grade");
-
- entity.Property(e => e.StuName)
- .HasMaxLength(50)
- .HasColumnName("stu_name");
-
- entity.Property(e => e.StuRemark)
- .HasMaxLength(255)
- .HasColumnName("stu_remark");
- });
-
- OnModelCreatingPartial(modelBuilder);
- }
-
- partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
- }
- }
数据库连接字符串获取
工具>连接到数据库
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。