gpt4 book ai didi

c# - 如何在代码中模拟多对多关系?

转载 作者:行者123 更新时间:2023-11-30 18:17:58 25 4
gpt4 key购买 nike

我在 C# 系统中工作,我需要为多对多关系建模,我想在其中手动构建模型(即我不想使用任何框架)。

我将通过一个简化的系统示例,然后解释问题:我有一个包含BookAuthor的图书馆,每本Book可以有很多Author,并且相同适用于作者

public class Book{
public string Title;
public List<Author> Authors;
}

public class Author{
public string Name;
public List<Book> Books;
}

现在,如果我想SELECT 包含所有作者的书籍;我会在 Book 类中编写一个函数,如下所示:

public List<Book> All(){
List<Book> Books = new List<Book>();
Books = //Query that brings all books and its Authors and populate them into the Books list.
}

现在我应该可以做这样的事情了:

 Book boo = new Book();
List<Book> books = boo.All();
Console.WriteLine(books[0].Authors[0].Name);

但我不能做的是:

 Console.WriteLine(books[0].Authors[0].Books[0].Title);

因为在此流程中 books[0].Authors[0].Books[0] 将为 null(或默认值)。所以我不会做一些半动态的东西并记住来自数据库服务器和客户端服务器的角度。

希望我的观点足够清楚。感谢您的宝贵时间。

最佳答案

我会做这样的事情来模拟数据库 n 对 n 的关系:

    public class DB
{
public class Book
{
public string Title;

public List<Author> Authors
{
get
{
return
BookAuthor.Connection.Where(ba => ba.Book.Title == this.Title)
.Select(ba => ba.Author)
.ToList();
}
}

public void AddAuthor(Author a)
{
var connection = new BookAuthor(this, a);

if (!BookAuthor.Connection.Exists(c => c.Author.Name == connection.Author.Name &&
c.Book.Title == connection.Book.Title))
BookAuthor.Connection.Add(connection);
}
}

public class Author
{
public string Name;

public List<Book> Books
{
get
{
return
BookAuthor.Connection.Where(ba => ba.Author.Name == this.Name)
.Select(ba => ba.Book)
.ToList();
}
}

public void AddBook(Book b)
{
var connection = new BookAuthor(b, this);

if (!BookAuthor.Connection.Exists(c => c.Author.Name == connection.Author.Name &&
c.Book.Title == connection.Book.Title))
BookAuthor.Connection.Add(connection);
}
}

private class BookAuthor
{
public Book Book { get; set; }
public Author Author { get; set; }

public static List<BookAuthor> Connection { get; } = new List<BookAuthor>();

public BookAuthor(Book book, Author author)
{
Book = book;
Author = author;
}
}
}

public void Run()
{
List<DB.Book> books = new List<DB.Book>()
{
new DB.Book() {Title = "Crime & Punishment"},
new DB.Book() {Title = "Karamazov"}
};

List<DB.Author> authors = new List<DB.Author>()
{
new DB.Author()
{
Name = "Dostoyevsky",
Books = { books[0] }
}
};
authors[0].AddBook(books[1]);
authors[0].AddBook(books[1]); // constraint

List<DB.Book> allBooksOfDostoyevsky = authors[0].Books;
var dost = authors[0].Books[0].Authors[0].Name; // Dostoyevsky
}

关于c# - 如何在代码中模拟多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42572783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com