如何檢查 EF Core 6 中急切加載的屬性的欄位是否為空?
uj5u.com熱心網友回復:
參考MS EF 檔案:
急切加載意味著從資料庫加載相關資料作為初始查詢的一部分。
然后,加載它并檢查它是否為空:
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Owner)
.ToList();
foreach(var blog in blogs)
{
var no_owner = blog.Owner == null; //< -- here
// ... more code
}
}
問(關于評論):如何在 Projections 中過濾?使用投影時似乎不起作用。
在投影中也檢查選擇中的空值:
var blogs =
db
.Posts
.Where(
p => p.Blog == null // <-- (1)
)
.Select(
p => new {
p.Title,
without_blog = p.Blog == null // <-- (2)
}
)
.ToList();
}
/*
SELECT p.Title,
b.BlogId IS NULL AS without_blog // <-- (2)
FROM Posts AS p
LEFT JOIN Blogs AS b ON p.BlogId = b.BlogId
WHERE b.BlogId IS NULL // <-- (1)
*/
(回答結束)
只為未來的自己(或未來的我)
我將全文粘貼在這里,因為我知道我需要它來幫助其他人。請大家自由地改進這個測驗,我知道它可以更好:)
添加包:
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
創建 dbcontext 和模型:
using Microsoft.EntityFrameworkCore;
public static class MyDebug
{
public static string sql {get; set; } = "";
public static void Capture(string query)
{
if (query.Contains("SELECT")) sql = query;
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; } = default!;
public DbSet<Post> Posts { get; set; } = default!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlite("Data Source=hello.db")
.LogTo(MyDebug.Capture);
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List<Post> Posts { get; set; } = new();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } = "";
public Blog? Blog { get; set; }
}
測驗:
public class ProjectionTest
{
[Fact]
public void TestProjection()
{
using (var db = new BloggingContext())
{
db.Database.Migrate();
var blogs =
db
.Posts
.Where(
p => p.Blog == null // <-- (1)
)
.Select(
p => new {
p.Title,
without_blog = p.Blog == null // <-- (2)
}
)
.ToList();
}
/*
SELECT p.Title,
b.BlogId IS NULL AS without_blog // <-- (2)
FROM Posts AS p
LEFT JOIN Blogs AS b ON p.BlogId = b.BlogId
WHERE b.BlogId IS NULL // <-- (1)
*/
Assert.Contains("b.BlogId IS NULL AS", MyDebug.sql);
Assert.Contains("WHERE b.BlogId IS NULL", MyDebug.sql);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/507004.html
