当前位置:   article > 正文

.Net Core6.0 Entity FrameWorkCore与SqlServer创建连接DBcontext上下文

.Net Core6.0 Entity FrameWorkCore与SqlServer创建连接DBcontext上下文
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.EntityFrameworkCore.Metadata;
  5. namespace Student.Manage.Api.Models
  6. {
  7. /// <summary>
  8. /// 添加Nuget包:
  9. /// Microsoft.EntityframeworkCore.Core
  10. /// Microsoft.EntityframeworkCore.SqlServer
  11. /// Microsoft.EntityframeworkCore.Tools
  12. /// Microsoft.EntityframeworkCore.Abstractions
  13. /// Microsoft.EntityframeworkCore.Relational
  14. /// </summary>
  15. public partial class TestDBContext : DbContext
  16. {
  17. public TestDBContext()
  18. {
  19. }
  20. public TestDBContext(DbContextOptions<TestDBContext> options)
  21. : base(options)
  22. {
  23. }
  24. /// <summary>
  25. /// Tb_Student测试实体(与数据库表结构设计保持一致)
  26. /// </summary>
  27. public virtual DbSet<Tb_Student> TbStudents { get; set; } = null!;
  28. /// <summary>
  29. /// 与数据库建立连接函数
  30. /// </summary>
  31. /// <param name="optionsBuilder"></param>
  32. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  33. {
  34. #region 与sqlserver数据库建立连接两种方式
  35. //第一种
  36. //optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=TestDB;Integrated Security=True;Trust Server Certificate=True");
  37. //第二种(在配置文件中设置数据库连接字符串)
  38. //"ConnectionStrings": {
  39. // "DbDefaultString": "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;Trust Server Certificate=True"
  40. //}
  41. optionsBuilder.UseSqlServer("name=ConnectionStrings:DbDefaultString");
  42. //第三种()
  43. //base.OnConfiguring(optionsBuilder);
  44. #endregion
  45. }
  46. protected override void OnModelCreating(ModelBuilder modelBuilder)
  47. {
  48. modelBuilder.Entity<Tb_Student>(entity =>
  49. {
  50. entity.ToTable("tb_Student");
  51. entity.Property(e => e.Id)
  52. .ValueGeneratedNever()
  53. .HasColumnName("id");
  54. entity.Property(e => e.StuAge).HasColumnName("stu_age");
  55. entity.Property(e => e.StuGender)
  56. .HasMaxLength(10)
  57. .HasColumnName("stu_gender")
  58. .IsFixedLength();
  59. entity.Property(e => e.StuGrade)
  60. .HasMaxLength(50)
  61. .HasColumnName("stu_grade");
  62. entity.Property(e => e.StuName)
  63. .HasMaxLength(50)
  64. .HasColumnName("stu_name");
  65. entity.Property(e => e.StuRemark)
  66. .HasMaxLength(255)
  67. .HasColumnName("stu_remark");
  68. });
  69. OnModelCreatingPartial(modelBuilder);
  70. }
  71. partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
  72. }
  73. }

数据库连接字符串获取

工具>连接到数据库

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/972994
推荐阅读
相关标签
  

闽ICP备14008679号