测试实体类(表结构)
public class User { public int user_id { get; set; } public string user_name { get; set; } } public class Book { public int book_id { get; set; } public string book_name { get; set; } public int user_id { get; set; } } //一对多关系 public class UserBooks : User { public List<Book> Books; public UserBooks() { Books = new List<Book>(); } } //一对一关系 public class UserBook : User { public Book MyBook; }
测试程序
public static void TestOneToMany() { using (var con = new MySqlConnection("Server=182.180.57.3;Database=test;port=3306;user id=root;password=123;")) { Console.WriteLine("==========下面是一对多的Demo==========="); var userBooks = con.Query<UserBooks, Book, UserBooks>(@"SELECT a.user_name,a.user_id,b.user_id,b.book_id, b.book_name FROM tab_user a INNER JOIN tab_book b ON a.user_id=b.user_id" , (user, book) => { user.Books.Add(book); return user; }, null, null, true, "user_id"); foreach (UserBooks ub in userBooks) { Console.Write(ub.user_id + "\t" + ub.user_name + "\t"); foreach (Book book in ub.Books) { Console.Write(book.book_id + " " + book.book_name + "\n"); } } Console.WriteLine("==========下面是一对一的Demo==========="); var userBook = con.Query<UserBook, Book, UserBook>(@"SELECT a.user_name,a.user_id,b.user_id,b.book_id, b.book_name FROM tab_user a INNER JOIN tab_book b ON a.user_id=b.user_id where a.user_id=3" , (user, book) => { user.MyBook = book; return user; }, null, null, true, "user_id").First<UserBook>(); Console.WriteLine(userBook.user_id + "\t" + userBook.user_name + "\t" + userBook.MyBook.book_id + "\t" + userBook.MyBook.book_name); Console.Read(); } }