直接贴代码了:

1. Program.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; namespace LazyLoading
{
class Program
{
static async Task Main()
{
var container = AppServices.Instance.Container;
var booksService = container.GetRequiredService<BooksService>();
await booksService.CreateDatabaseAsync();
booksService.GetBooksWithLazyLoading();
booksService.GetBooksWithEagerLoading();
booksService.GetBooksWithExplicitLoading();
await booksService.DeleteDatabaseAsync();
}
}
}

2. Book

using System.Collections.Generic;

namespace LazyLoading
{
public class Book
{
public Book(int bookId, string title) => (BookId, Title) = (bookId, title); public Book(int bookId, string title, string publisher) => (BookId, Title, Publisher) = (bookId, title, publisher); public int BookId { get; set; }
public string Title { get; set; }
public string? Publisher { get; set; }
public virtual ICollection<Chapter> Chapters { get; } = new List<Chapter>();
public int? AuthorId { get; set; }
public int? ReviewerId { get; set; }
public int? EditorId { get; set; } public virtual User? Author { get; set; }
public virtual User? Reviewer { get; set; }
public virtual User? Editor { get; set; }
}
}

3. BookConfiguration

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace LazyLoading
{
internal class BookConfiguration : IEntityTypeConfiguration<Book>
{
public void Configure(EntityTypeBuilder<Book> builder)
{
builder.HasMany(b => b.Chapters)
.WithOne(c => c.Book)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(b => b.Author)
.WithMany(a => a.WrittenBooks)
.HasForeignKey(b => b.AuthorId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(b => b.Reviewer)
.WithMany(r => r.ReviewedBooks)
.HasForeignKey(b => b.ReviewerId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(b => b.Editor)
.WithMany(e => e.EditedBooks)
.HasForeignKey(e => e.EditorId)
.OnDelete(DeleteBehavior.Restrict);
builder.Property(b => b.Title)
.HasMaxLength()
.IsRequired();
builder.Property(b => b.Publisher)
.HasMaxLength()
.IsRequired(false);
}
}
}

4. User

using System.Collections.Generic;

namespace LazyLoading
{
public class User
{
public User(int userId, string name) => (UserId, Name) = (userId, name); public int UserId { get; set; }
public string Name { get; set; }
public virtual List<Book> WrittenBooks { get; } = new List<Book>();
public virtual List<Book> ReviewedBooks { get; } = new List<Book>();
public virtual List<Book> EditedBooks { get; } = new List<Book>();
}
}

5. UserConfiguration

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace LazyLoading
{
internal class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasMany(a => a.WrittenBooks)
.WithOne(nameof(Book.Author))
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(r => r.ReviewedBooks)
.WithOne(nameof(Book.Reviewer))
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(e => e.EditedBooks)
.WithOne(nameof(Book.Editor))
.OnDelete(DeleteBehavior.Restrict);
}
}
}

6. Chapter

namespace LazyLoading
{
public class Chapter
{
public Chapter(int chapterId, int number, string title) =>
(ChapterId, Number, Title) = (chapterId, number, title); public int ChapterId { get; set; }
public int Number { get; set; }
public string Title { get; set; }
public int BookId { get; set; }
public virtual Book? Book { get; set; }
}
}

7. ChapterConfiguration

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace LazyLoading
{
internal class ChapterConfiguration : IEntityTypeConfiguration<Chapter>
{
public void Configure(EntityTypeBuilder<Chapter> builder)
{
builder.HasOne(c => c.Book)
.WithMany(b => b.Chapters)
.HasForeignKey(c => c.BookId);
}
}
}

8. BooksContext

using Microsoft.EntityFrameworkCore;

#nullable disable

namespace LazyLoading
{
public class BooksContext : DbContext
{
public BooksContext(DbContextOptions<BooksContext> options)
: base(options) { } public DbSet<Book> Books { get; private set; }
public DbSet<Chapter> Chapters { get; private set; }
public DbSet<User> Users { get; private set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new BookConfiguration());
modelBuilder.ApplyConfiguration(new ChapterConfiguration());
modelBuilder.ApplyConfiguration(new UserConfiguration()); SeedData(modelBuilder);
} private User[] _users = new[]
{
new User(, "Christian Nagel"),
new User(, "Istvan Novak"),
new User(, "Charlotte Kughen")
};
private Book _book = new Book(, "Professional C# 7 and .NET Core 2.0", "Wrox Press");
private Chapter[] _chapters = new[]
{
new Chapter(, , ".NET Applications and Tools"),
new Chapter(, , "Core C#"),
new Chapter(, , "Entity Framework Core")
}; protected void SeedData(ModelBuilder modelBuilder)
{
_book.AuthorId = ;
_book.ReviewerId = ;
_book.EditorId = ;
foreach (var c in _chapters)
{
c.BookId = ;
} modelBuilder.Entity<User>().HasData(_users);
modelBuilder.Entity<Book>().HasData(_book);
modelBuilder.Entity<Chapter>().HasData(_chapters);
}
}
}

9. BooksService

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Linq;
using System.Threading.Tasks; namespace LazyLoading
{
public class BooksService
{
private readonly BooksContext _booksContext;
public BooksService(BooksContext booksContext)
{
_booksContext = booksContext ?? throw new ArgumentNullException(nameof(booksContext));
} public void GetBooksWithLazyLoading()
{
var books = _booksContext.Books.Where(b => b.Publisher.StartsWith("Wrox")); foreach (var book in books)
{
Console.WriteLine(book.Title);
Console.WriteLine(book.Publisher);
foreach (var chapter in book.Chapters)
{
Console.WriteLine($"{chapter.Number}. {chapter.Title}");
}
Console.WriteLine($"author: {book.Author?.Name}");
Console.WriteLine($"reviewer: {book.Reviewer?.Name}");
Console.WriteLine($"editor: {book.Editor?.Name}");
}
} public void GetBooksWithExplicitLoading()
{
var books = _booksContext.Books.Where(b => b.Publisher.StartsWith("Wrox")); foreach (var book in books)
{
Console.WriteLine(book.Title);
EntityEntry<Book> entry = _booksContext.Entry(book);
entry.Collection(b => b.Chapters).Load(); foreach (var chapter in book.Chapters)
{
Console.WriteLine($"{chapter.Number}. {chapter.Title}");
} entry.Reference(b => b.Author).Load();
Console.WriteLine($"author: {book.Author?.Name}"); entry.Reference(b => b.Reviewer).Load();
Console.WriteLine($"reviewer: {book.Reviewer?.Name}"); entry.Reference(b => b.Editor).Load();
Console.WriteLine($"editor: {book.Editor?.Name}");
}
} public void GetBooksWithEagerLoading()
{
var books = _booksContext.Books
.Where(b => b.Publisher.StartsWith("Wrox"))
.Include(b => b.Chapters)
.Include(b => b.Author)
.Include(b => b.Reviewer)
.Include(b => b.Editor); foreach (var book in books)
{
Console.WriteLine(book.Title);
foreach (var chapter in book.Chapters)
{
Console.WriteLine($"{chapter.Number}. {chapter.Title}");
}
Console.WriteLine($"author: {book.Author?.Name}");
Console.WriteLine($"reviewer: {book.Reviewer?.Name}");
Console.WriteLine($"editor: {book.Editor?.Name}");
}
} public async Task DeleteDatabaseAsync()
{
Console.Write("Delete the database? ");
string input = Console.ReadLine(); if (input.ToLower() == "y")
{
bool deleted = await _booksContext.Database.EnsureDeletedAsync();
Console.WriteLine($"database deleted: {deleted}");
}
} public async Task CreateDatabaseAsync()
{
bool created = await _booksContext.Database.EnsureCreatedAsync();
string info = created ? "created" : "already exists";
Console.WriteLine($"database {info}");
}
}
}

10. AppServices

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.IO; namespace LazyLoading
{
public class AppServices
{
private const string BooksConnection = nameof(BooksConnection); static AppServices()
{
Configuration = GetConfiguration();
} private AppServices()
{
Container = GetServiceProvider();
} public static AppServices Instance { get; } = new AppServices(); public IServiceProvider Container { get; } public static IConfiguration GetConfiguration() =>
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build(); public static IConfiguration Configuration { get; } private ServiceProvider GetServiceProvider() =>
new ServiceCollection()
.AddLogging(config =>
{
config
.AddConsole()
.AddDebug()
.AddFilter(level => level > LogLevel.Debug);
})
.AddTransient<BooksService>()
.AddDbContext<BooksContext>(options =>
{
options
.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString(BooksConnection));
})
.BuildServiceProvider();
}
}

11. appsettings.json

{
"ConnectionStrings": {
"BooksConnection": "server=(localdb)\\MSSQLLocalDb;database=BooksLazy;trusted_connection=true"
}
}

代码下载:https://files.cnblogs.com/files/Music/EntityFrameworkCore-Sample-LazyLoading.rar

谢谢浏览!

最新文章

  1. compositionEnd 和 input 事件(中文输入法问题)
  2. PYTHON黑帽编程1.5 使用WIRESHARK练习网络协议分析
  3. Android中如何像 360 一样优雅的杀死后台Service而不启动
  4. IT痴汉的工作现状24-Just for fun
  5. VIM、GVIM在WINDOWS下中文乱码的终极解决方案
  6. java中的Integer的toBinaryString()方法
  7. 一分钟学会(一):.NET之正则表达式
  8. mstsc命令详解
  9. 支持IE6的树形节结构TreeTable
  10. 39. Combination Sum
  11. Java中如何创建进程(转)
  12. shell入门之变量测试 分类: 学习笔记 linux ubuntu 2015-07-10 15:49 31人阅读 评论(0) 收藏
  13. sublime2 c++的一些使用配置
  14. iOS 知识点
  15. 基于FFMPEG的跨平台播放器实现(二)
  16. 如何通过 ZAZ-020 电容指纹模块采集指纹信息?
  17. JS实现数组去重方法总结(六种方法)
  18. 菜鸟玩云计算之廿一: saltstack之pillar
  19. Golang源码探索(三) GC的实现原理(转)
  20. Dubbo 源码分析 - 集群容错之 LoadBalance

热门文章

  1. 【趣学程序】Linux上安装Tengine(Nginx)
  2. WPF的DataGrid的某个列绑定数据的三种方法(Binding、Converter、DataTrigger)
  3. vs code搭建Django环境
  4. Java 小游戏 - 井字棋 v1.0 (初步完成) (2018.4.16更新)
  5. Clean Code
  6. 面试题-JavaScript交换两个变量的方法
  7. Shadow broker=&gt;fuzzbunch+metasploit 攻击外网测试以及metasploit大批量扫描目标IP
  8. tableView左划自定义带图片按钮
  9. 【JavaWeb】JSTL标签库
  10. [视频教程] ubuntu系统下安装最新版PHP7.3.X环境