前言:
本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作。
本系列文章主要参考资料:
微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/getting-started/?view=aspnetcore-2.1&tabs=windows
《Pro ASP.NET MVC 5》、《锋利的 jQuery》
此系列皆使用 VS2017+C# 作为开发环境。如果有什么问题或者意见欢迎在留言区进行留言。
项目 github 地址:https://github.com/NanaseRuri/LibraryDemo
本章内容:对图书馆系统组成的简要分析。以及对域模型以及相应数据库的建立。
知识点:EF 多对多关系的建立、控制器以及动作方法的创建
一、EF 多对多关系的建立
在上一章中,我假设书架和书籍关系为多对一的关系,而实际上一本书可以放在不同的书架上,如我们学校中的两个图书馆中不同的书架,因此需要对现有的模型进行更新。
在 EF 中,如果在两个模型类中同时使用基于另外一方的 ICollection 时会出现异常,因为 EF 无法确定它们之间的外键关系,因此需要引入一个中间类:
1 public class BookMiddle
2 {
3 public int BookMiddleId { get; set; }
4 public string BookId { get; set; }
5 public int BookshelfId { get; set; }
6 public Book Book { get; set; }
7 public Bookshelf Bookshelf { get; set; }
8 }
同时对 Book 和 Bookshelf 类进行更改:
1 public class Book
2 {
3 ///
4 /// 二维码
5 ///
6 [Key]
7 public string BarCode { get; set; }
8
9 public string ISBN { get; set; }
10
11 ///
12 /// 书名
13 ///
14 [Required]
15 public string Name { get; set; }
16
17 ///
18 /// 取书号
19 ///
20 public string FetchBookNumber { get; set; }
21
22 ///
23 /// 所在书架
24 ///
25 //public Bookshelf Bookshelf { get; set; }
26 public ICollection BookMiddles { get; set; }27
28 ///
29 /// 借出时间
30 ///
31 public DateTime BorrowTime { get; set; }
32
33 ///
34 /// 到期时间
35 ///
36 public DateTime MatureTime { get; set; }
37
38 ///
39 /// 是否续借过
40 ///
41 public bool Renewed { get; set; }
42
43 ///
44 /// 持有者,指定外键
45 ///
46 public Student Keeper { get; set; }
47 }
1 public class Bookshelf
2 {
3 ///
4 /// 书架ID
5 ///
6 [Key]
7 public int BookshelfId { get; set; }
8
9 ///
10 /// 书架的书籍类别
11 ///
12
13 [Required]
14 public string Sort { get; set; }
15 ///
16 /// 最小取书号
17 ///
18 [Required]
19 public string MinFetchNumber { get; set; }
20 [Required]
21 public string MaxFetchNumber { get; set; }
22
23 ///
24 /// 书架位置
25 ///
26 [Required]
27 public string Location { get; set; }
28
29 ///
30 /// 全部藏书
31 ///
32 //public ICollection Books { get; set; }
33 public ICollection BookMiddles { get; set; }
34 }
在 LendingInfoDBContext 添加 BookMiddle 表:
public class LendingInfoDbContext:DbContext
{
public LendingInfoDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Books { get; set; }
public DbSet BooksDetail { get; set; }
public DbSet Bookshelves { get; set; }
public DbSet Students { get; set; }
public DbSet RecommendedBooks { get; set; }
public DbSet BookMiddles { get; set; }
}
为数据库添加迁移:
add-migration AddBookMiddles -c LibraryDemo.Data.LendingInfoDbContext
更新数据库:
update-database -c LibraryDemo.Data.LendingInfoDbContext
查看当前数据库结构:
原文出处:https://www.cnblogs.com/gokoururi/p/10160374.html



