CSharp: donet 6 or 7 Migrations with Entity Framework Core 6 or 7

 初始化创建表和数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    /// <summary>
    ///
    ///Entity
    /// </summary>
    public class Product
    {
 
        public Product() { }   
 
        public int Id { get; set; }
        public string Name { get; set; }
        public int Quantity { get; set; }
        public float Price { get; set; }
    }
 
    /// <summary>
    /// Entity
    /// geovindu, Geovin Du
    /// </summary>
    public class Customer
    {
 
        public Customer() {
 
     
        }
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
 
    /// <summary>
    ///
    /// </summary>
    public class ECommerceDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Customer> Customers { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=DESKTOP-NQK85G5\\GEOVIN2008;Database=geovinduCoreDBA;User Id=sa;Password=geovindu;");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>();
            modelBuilder.Entity<Customer>();
            base.OnModelCreating(modelBuilder);
        }
    }
 
 
    /// <summary>
    /// 初始化创建表格
    /// </summary>
    [DbContext(typeof(ECommerceDbContext))]
    partial class ECommerceDbContextModelSnapshot : ModelSnapshot
    {
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            //ProductVersion
            modelBuilder
                .HasAnnotation("ProductVersion", "6.0.6")
                .HasAnnotation("Relational:MaxIdentifierLength", 128);
 
            SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
            //Customer
            modelBuilder.Entity("Customer", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int");
 
                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
 
                    b.Property<string>("FirstName")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");
 
                    b.Property<string>("LastName")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");
 
                    b.HasKey("Id");
 
                    b.ToTable("Customers");
                });
            //Product
            modelBuilder.Entity("Product", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int");
 
                    SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
 
                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("nvarchar(max)");
 
                    b.Property<float>("Price")
                        .HasColumnType("real");
 
                    b.Property<int>("Quantity")
                        .HasColumnType("int");
 
                    b.HasKey("Id");
 
                    b.ToTable("Products");
                });
#pragma warning restore 612, 618
        }
    }

  

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//初始化表格至数据库
ECommerceDbContext context = new();
await context.Database.MigrateAsync();
 
//
context = new ECommerceDbContext();
List<Customer> customers = new List<Customer>();
//添加
Customer customer=new Customer();
customer.FirstName= "涂";
customer.LastName = "聚文";
customers.Add(customer);
customer = new Customer();
customer.FirstName = "Du";
customer.LastName = "geovind";
customers.Add(customer);
context.Customers.AddRange(customers);
int k=context.SaveChanges();
if (k > 0)
{
    Console.WriteLine("ok");
}
//查询
var custer=context.Customers.FirstOrDefault();
Console.WriteLine(custer.FirstName+","+custer.LastName);

  

输出:

 

 

 

 appsettings.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Persistence": {
    "Provider": "MSSQL"
  },
  "ConnectionStrings": {
    "GeovinDuDbContext": "Data Source=DESKTOP-NQK85G5\\GEOVIN2008;Initial Catalog=EntityFramework6;Integrated Security=SSPI;"
  }
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using DuEntity;
 
 
 
namespace DuUtilitieDB
{
 
    /// <summary>
    /// geovindu
    /// </summary>
    public class DuDbContext : DbContext
    {
 
        public DbSet<DuProduct> DuProduct { get; set; }
 
        public DbSet<DuCustomer> DuCustomer { get; set; }
       
        public DbSet<Student> Students { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
       
 
 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
 
            //读取配置文件
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory()) //Environment.CurrentDirectory
                .AddJsonFile("appsettings.json")
                .AddInMemoryCollection()
                .Build();
            var connStr = config["ConnectionStrings:GeovinDuDbContext"];
 
 
            // optionsBuilder.UseSqlServer("Server=DESKTOP-NQK85G5\\GEOVIN2008;Database=geovindu;User Id=sa;Password=geovindu;");
            optionsBuilder.UseSqlServer(connStr);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
 
            modelBuilder.Entity<DuProduct>();
            modelBuilder.Entity<DuCustomer>();
 
            //modelBuilder.Entity<Student>();
            //modelBuilder.Entity<Product>();
            //modelBuilder.Entity<Category>();
            //modelBuilder.Entity<Customer>();
 
 
            base.OnModelCreating(modelBuilder);
 
 
        }
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/// <summary>
/// 存储过程输出参数
/// EF Core 7
/// </summary>
/// <param name="category">输入</param>
/// <param name="ategoryID">输出参数</param>
/// <returns></returns>
public int AddOutProc(Category category,out int categoryID)
{
    int addok = 0;
 
    try
    {
         
        using (var context = new DuDbContext())
        {
            addok = 0;
 
            var parameter = new SqlParameter[]
           {
 
                new SqlParameter("@CategoryName",SqlDbType.NVarChar,200),
                new SqlParameter("@CategoryId",SqlDbType.Int),
 
              // ParameterName = "@CategoryId",
               // SqlDbType = System.Data.SqlDbType.Int,
              // Direction = System.Data.ParameterDirection.Output
           };
        parameter[0].Value = category.CategoryName;
         parameter[1].Direction = ParameterDirection.Output;                
 
         // addok = context.Database.ExecuteSqlRaw("dbo.proc_Insert_CategoriesOutput @CategoryName, @CategoryId OUTPUT", parameter);
 
            addok = context.Database.ExecuteSqlRawAsync("dbo.proc_Insert_CategoriesOutput @CategoryName, @CategoryId OUTPUT",parameter).Result;
 
            categoryID = (int)parameter[1].Value;
            //context.Database.ExecuteSqlAsync($"UpdateStudentMark @Id={id}, @Mark={mark}");
            
        }
    }
    catch (Exception ex)
    {
        categoryID = 0;
        ex.Message.ToString();
    }
    return addok;
}

  

 

posted @   ®Geovin Du Dream Park™  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-02-04 java: imap Receive Email
2009-02-04 C#2.0 从sql server 中读取二进制图片
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示