Program.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. namespace Sqlite_EF_Test
  9. {
  10. internal class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. test();
  15. Console.ReadKey();
  16. }
  17. public static async void test()
  18. {
  19. try
  20. {
  21. // 初始化数据库服务
  22. var dbService = new DatabaseService();
  23. dbService.InitializeDatabase();
  24. // 创建用户
  25. var user = await dbService.CreateUserAsync("张三", "zhangsan@example.com");
  26. Console.WriteLine($"创建用户: {user.Name}, ID: {user.Id}");
  27. // 创建产品
  28. var product = await dbService.CreateProductAsync("笔记本电脑", 5999.99m, 10);
  29. Console.WriteLine($"创建产品: {product.Name}, 价格: {product.Price}");
  30. // 查询所有用户
  31. var users = await dbService.GetAllUsersAsync();
  32. Console.WriteLine("所有用户:");
  33. foreach (var u in users)
  34. {
  35. Console.WriteLine($" {u.Id}: {u.Name} ({u.Email})");
  36. }
  37. // 查询所有产品
  38. var products = await dbService.GetAllProductsAsync();
  39. Console.WriteLine("所有产品:");
  40. foreach (var p in products)
  41. {
  42. Console.WriteLine($" {p.Id}: {p.Name} - ¥{p.Price} (库存: {p.Stock})");
  43. }
  44. }
  45. catch (Exception ex)
  46. {
  47. Console.WriteLine($"发生错误: {ex.Message}");
  48. }
  49. }
  50. }
  51. [Table("Users")]
  52. public class User
  53. {
  54. [Key]
  55. public int Id { get; set; }
  56. [Required]
  57. [MaxLength(100)]
  58. public string Name { get; set; }
  59. [MaxLength(255)]
  60. public string Email { get; set; }
  61. public DateTime CreatedAt { get; set; }
  62. }
  63. [Table("Products")]
  64. public class Product
  65. {
  66. [Key]
  67. public int Id { get; set; }
  68. [Required]
  69. [MaxLength(200)]
  70. public string Name { get; set; }
  71. public decimal Price { get; set; }
  72. public int Stock { get; set; }
  73. }
  74. public class AppDbContext : DbContext
  75. {
  76. public DbSet<User> Users { get; set; }
  77. public DbSet<Product> Products { get; set; }
  78. private readonly string _connectionString;
  79. public AppDbContext()
  80. {
  81. var dbPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "app.db");
  82. _connectionString = $"Data Source={dbPath}";
  83. }
  84. public AppDbContext(string connectionString)
  85. {
  86. _connectionString = connectionString;
  87. }
  88. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  89. {
  90. if (!optionsBuilder.IsConfigured)
  91. {
  92. optionsBuilder.UseSqlite(_connectionString);
  93. }
  94. }
  95. protected override void OnModelCreating(ModelBuilder modelBuilder)
  96. {
  97. modelBuilder.Entity<User>(entity =>
  98. {
  99. entity.HasKey(e => e.Id);
  100. entity.Property(e => e.CreatedAt)
  101. .HasDefaultValueSql("CURRENT_TIMESTAMP");
  102. });
  103. modelBuilder.Entity<Product>(entity =>
  104. {
  105. entity.HasKey(e => e.Id);
  106. entity.HasIndex(e => e.Name);
  107. });
  108. base.OnModelCreating(modelBuilder);
  109. }
  110. }
  111. public class DatabaseService
  112. {
  113. private readonly string _connectionString;
  114. public DatabaseService(string connectionString = null)
  115. {
  116. if (string.IsNullOrEmpty(connectionString))
  117. {
  118. var dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app.db");
  119. _connectionString = $"Data Source={dbPath}";
  120. }
  121. else
  122. {
  123. _connectionString = connectionString;
  124. }
  125. }
  126. // 初始化数据库
  127. public void InitializeDatabase()
  128. {
  129. using (var context = new AppDbContext(_connectionString))
  130. {
  131. context.Database.EnsureCreated();
  132. }
  133. }
  134. // 用户相关操作
  135. public async Task<User> CreateUserAsync(string name, string email)
  136. {
  137. var user = new User
  138. {
  139. Name = name,
  140. Email = email,
  141. CreatedAt = DateTime.Now
  142. };
  143. using (var context = new AppDbContext(_connectionString))
  144. {
  145. context.Users.Add(user);
  146. await context.SaveChangesAsync();
  147. }
  148. return user;
  149. }
  150. public async Task<List<User>> GetAllUsersAsync()
  151. {
  152. using (var context = new AppDbContext(_connectionString))
  153. {
  154. return await context.Users.ToListAsync();
  155. }
  156. }
  157. public async Task<User> GetUserByIdAsync(int id)
  158. {
  159. using (var context = new AppDbContext(_connectionString))
  160. {
  161. return await context.Users.FindAsync(id);
  162. }
  163. }
  164. public async Task<User> UpdateUserAsync(int id, string name, string email)
  165. {
  166. using (var context = new AppDbContext(_connectionString))
  167. {
  168. var user = await context.Users.FindAsync(id);
  169. if (user != null)
  170. {
  171. user.Name = name;
  172. user.Email = email;
  173. await context.SaveChangesAsync();
  174. }
  175. return user;
  176. }
  177. }
  178. public async Task<bool> DeleteUserAsync(int id)
  179. {
  180. using (var context = new AppDbContext(_connectionString))
  181. {
  182. var user = await context.Users.FindAsync(id);
  183. if (user != null)
  184. {
  185. context.Users.Remove(user);
  186. await context.SaveChangesAsync();
  187. return true;
  188. }
  189. return false;
  190. }
  191. }
  192. // 产品相关操作
  193. public async Task<Product> CreateProductAsync(string name, decimal price, int stock)
  194. {
  195. using (var context = new AppDbContext(_connectionString))
  196. {
  197. var product = new Product
  198. {
  199. Name = name,
  200. Price = price,
  201. Stock = stock
  202. };
  203. context.Products.Add(product);
  204. await context.SaveChangesAsync();
  205. return product;
  206. }
  207. }
  208. public async Task<List<Product>> GetAllProductsAsync()
  209. {
  210. using (var context = new AppDbContext(_connectionString))
  211. {
  212. return await context.Products.ToListAsync();
  213. }
  214. }
  215. public async Task<Product> GetProductByIdAsync(int id)
  216. {
  217. using (var context = new AppDbContext(_connectionString))
  218. return await context.Products.FindAsync(id);
  219. }
  220. public async Task<Product> UpdateProductAsync(int id, string name, decimal price, int stock)
  221. {
  222. using (var context = new AppDbContext(_connectionString))
  223. {
  224. var product = await context.Products.FindAsync(id);
  225. if (product != null)
  226. {
  227. product.Name = name;
  228. product.Price = price;
  229. product.Stock = stock;
  230. await context.SaveChangesAsync();
  231. }
  232. return product;
  233. }
  234. }
  235. }
  236. }