新建文本文档.txt 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. 我来为您提供一个在 .NET Framework 4.8 环境下使用 Entity Framework 和 Microsoft.Data.Sqlite 管理 SQLite 数据库的实现方案。
  2. 1. 项目配置
  3. 首先需要安装必要的 NuGet 包:
  4. <packages>
  5. <package id="Microsoft.Data.Sqlite" version="5.0.17" targetFramework="net48" />
  6. <package id="Microsoft.EntityFrameworkCore" version="3.1.32" targetFramework="net48" />
  7. <package id="Microsoft.EntityFrameworkCore.Sqlite" version="3.1.32" targetFramework="net48" />
  8. <package id="System.Memory" version="4.5.4" targetFramework="net48" />
  9. <package id="System.Buffers" version="4.5.1" targetFramework="net48" />
  10. <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
  11. <package id="System.Runtime.CompilerServices.Unsafe" version="4.7.1" targetFramework="net48" />
  12. </packages>
  13. 2. 数据模型定义
  14. using System.ComponentModel.DataAnnotations;
  15. using System.ComponentModel.DataAnnotations.Schema;
  16. [Table("Users")]
  17. public class User
  18. {
  19. [Key]
  20. public int Id { get; set; }
  21. [Required]
  22. [MaxLength(100)]
  23. public string Name { get; set; }
  24. [MaxLength(255)]
  25. public string Email { get; set; }
  26. public DateTime CreatedAt { get; set; }
  27. }
  28. [Table("Products")]
  29. public class Product
  30. {
  31. [Key]
  32. public int Id { get; set; }
  33. [Required]
  34. [MaxLength(200)]
  35. public string Name { get; set; }
  36. public decimal Price { get; set; }
  37. public int Stock { get; set; }
  38. }
  39. 3. DbContext 实现
  40. using Microsoft.EntityFrameworkCore;
  41. using System.IO;
  42. public class AppDbContext : DbContext
  43. {
  44. public DbSet<User> Users { get; set; }
  45. public DbSet<Product> Products { get; set; }
  46. private readonly string _connectionString;
  47. public AppDbContext()
  48. {
  49. var dbPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "app.db");
  50. _connectionString = $"Data Source={dbPath}";
  51. }
  52. public AppDbContext(string connectionString)
  53. {
  54. _connectionString = connectionString;
  55. }
  56. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  57. {
  58. if (!optionsBuilder.IsConfigured)
  59. {
  60. optionsBuilder.UseSqlite(_connectionString);
  61. }
  62. }
  63. protected override void OnModelCreating(ModelBuilder modelBuilder)
  64. {
  65. modelBuilder.Entity<User>(entity =>
  66. {
  67. entity.HasKey(e => e.Id);
  68. entity.Property(e => e.CreatedAt)
  69. .HasDefaultValueSql("CURRENT_TIMESTAMP");
  70. });
  71. modelBuilder.Entity<Product>(entity =>
  72. {
  73. entity.HasKey(e => e.Id);
  74. entity.HasIndex(e => e.Name);
  75. });
  76. base.OnModelCreating(modelBuilder);
  77. }
  78. }
  79. 4. 数据库服务封装
  80. using Microsoft.EntityFrameworkCore;
  81. using System;
  82. using System.Collections.Generic;
  83. using System.Linq;
  84. using System.Threading.Tasks;
  85. public class DatabaseService
  86. {
  87. private readonly string _connectionString;
  88. public DatabaseService(string connectionString = null)
  89. {
  90. if (string.IsNullOrEmpty(connectionString))
  91. {
  92. var dbPath = System.IO.Path.Combine(
  93. System.AppDomain.CurrentDomain.BaseDirectory, "app.db");
  94. _connectionString = $"Data Source={dbPath}";
  95. }
  96. else
  97. {
  98. _connectionString = connectionString;
  99. }
  100. }
  101. // 初始化数据库
  102. public void InitializeDatabase()
  103. {
  104. using var context = new AppDbContext(_connectionString);
  105. context.Database.EnsureCreated();
  106. }
  107. // 用户相关操作
  108. public async Task<User> CreateUserAsync(string name, string email)
  109. {
  110. using var context = new AppDbContext(_connectionString);
  111. var user = new User
  112. {
  113. Name = name,
  114. Email = email,
  115. CreatedAt = DateTime.Now
  116. };
  117. context.Users.Add(user);
  118. await context.SaveChangesAsync();
  119. return user;
  120. }
  121. public async Task<List<User>> GetAllUsersAsync()
  122. {
  123. using var context = new AppDbContext(_connectionString);
  124. return await context.Users.ToListAsync();
  125. }
  126. public async Task<User> GetUserByIdAsync(int id)
  127. {
  128. using var context = new AppDbContext(_connectionString);
  129. return await context.Users.FindAsync(id);
  130. }
  131. public async Task<User> UpdateUserAsync(int id, string name, string email)
  132. {
  133. using var context = new AppDbContext(_connectionString);
  134. var user = await context.Users.FindAsync(id);
  135. if (user != null)
  136. {
  137. user.Name = name;
  138. user.Email = email;
  139. await context.SaveChangesAsync();
  140. }
  141. return user;
  142. }
  143. public async Task<bool> DeleteUserAsync(int id)
  144. {
  145. using var context = new AppDbContext(_connectionString);
  146. var user = await context.Users.FindAsync(id);
  147. if (user != null)
  148. {
  149. context.Users.Remove(user);
  150. await context.SaveChangesAsync();
  151. return true;
  152. }
  153. return false;
  154. }
  155. // 产品相关操作
  156. public async Task<Product> CreateProductAsync(string name, decimal price, int stock)
  157. {
  158. using var context = new AppDbContext(_connectionString);
  159. var product = new Product
  160. {
  161. Name = name,
  162. Price = price,
  163. Stock = stock
  164. };
  165. context.Products.Add(product);
  166. await context.SaveChangesAsync();
  167. return product;
  168. }
  169. public async Task<List<Product>> GetAllProductsAsync()
  170. {
  171. using var context = new AppDbContext(_connectionString);
  172. return await context.Products.ToListAsync();
  173. }
  174. public async Task<Product> GetProductByIdAsync(int id)
  175. {
  176. using var context = new AppDbContext(_connectionString);
  177. return await context.Products.FindAsync(id);
  178. }
  179. public async Task<Product> UpdateProductAsync(int id, string name, decimal price, int stock)
  180. {
  181. using var context = new AppDbContext(_connectionString);
  182. var product = await context.Products.FindAsync(id);
  183. if (product != null)
  184. {
  185. product.Name = name;
  186. product.Price = price;
  187. product.Stock = stock;
  188. await context.SaveChangesAsync();
  189. }
  190. return product;
  191. }
  192. }
  193. 5. 使用示例
  194. using System;
  195. using System.Threading.Tasks;
  196. class Program
  197. {
  198. static async Task Main(string[] args)
  199. {
  200. try
  201. {
  202. // 初始化数据库服务
  203. var dbService = new DatabaseService();
  204. dbService.InitializeDatabase();
  205. // 创建用户
  206. var user = await dbService.CreateUserAsync("张三", "zhangsan@example.com");
  207. Console.WriteLine($"创建用户: {user.Name}, ID: {user.Id}");
  208. // 创建产品
  209. var product = await dbService.CreateProductAsync("笔记本电脑", 5999.99m, 10);
  210. Console.WriteLine($"创建产品: {product.Name}, 价格: {product.Price}");
  211. // 查询所有用户
  212. var users = await dbService.GetAllUsersAsync();
  213. Console.WriteLine("所有用户:");
  214. foreach (var u in users)
  215. {
  216. Console.WriteLine($" {u.Id}: {u.Name} ({u.Email})");
  217. }
  218. // 查询所有产品
  219. var products = await dbService.GetAllProductsAsync();
  220. Console.WriteLine("所有产品:");
  221. foreach (var p in products)
  222. {
  223. Console.WriteLine($" {p.Id}: {p.Name} - ¥{p.Price} (库存: {p.Stock})");
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. Console.WriteLine($"发生错误: {ex.Message}");
  229. }
  230. Console.ReadKey();
  231. }
  232. }
  233. 6. 配置文件 (App.config)
  234. <?xml version="1.0" encoding="utf-8"?>
  235. <configuration>
  236. <configSections>
  237. <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  238. </configSections>
  239. <startup>
  240. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  241. </startup>
  242. <entityFramework>
  243. <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqliteConnectionFactory, EntityFramework.Sqlite">
  244. </defaultConnectionFactory>
  245. <providers>
  246. <provider invariantName="Microsoft.Data.Sqlite"
  247. type="Microsoft.Data.Sqlite.SqliteProviderServices, Microsoft.Data.Sqlite" />
  248. </providers>
  249. </entityFramework>
  250. <system.data>
  251. <DbProviderFactories>
  252. <remove invariant="Microsoft.Data.Sqlite" />
  253. <add name="SQLite Data Provider"
  254. invariant="Microsoft.Data.Sqlite"
  255. description=".NET Data Provider for SQLite"
  256. type="Microsoft.Data.Sqlite.SqliteFactory, Microsoft.Data.Sqlite" />
  257. </DbProviderFactories>
  258. </system.data>
  259. </configuration>
  260. 关键要点
  261. 1. 版本兼容性: 使用 Entity Framework Core 3.1,这是支持 .NET Framework 4.8 的最后一个版本
  262. 2. SQLite 驱动: 使用 Microsoft.Data.Sqlite 而不是传统的 System.Data.SQLite
  263. 3. 异步支持: 所有数据库操作都提供异步版本以提高性能
  264. 4. 连接字符串: 支持自定义数据库路径,默认在应用程序目录下创建 app.db
  265. 5. 数据库初始化: 使用 EnsureCreated() 方法自动创建数据库和表结构
  266. 这个方案提供了完整的 SQLite 数据库管理功能,包括增删改查操作,并且完全兼容 .NET Framework 4.8 环境。