簡體   English   中英

EFCore 急切加載問題

[英]EFCore eager loading issue

我有點困惑為什么這在 EF Core 3.1.8 和 SQLite 中不起作用。 我在兩個具有 int 和 Guid 的實體之間有一個復合外鍵關系。 當我嘗試使用商店部分預先加載所有商店時,StoreSection 導航屬性未返回任何結果。

我檢查了創建的表,數據按預期保存。 我檢查了生成的優化的 sql,當我直接運行它時,結果返回我期望的。 下面是一個演示該問題的控制台應用程序。

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestEfcore
{
    class Program
    {
        static void Main()
        {
            Guid userId = Guid.NewGuid();

            using (var context = new GroceryManagerContext())
            {
                var newStore = new Store
                {
                    Name = "Grocery World",
                    GroceryManagerUserId = userId
                };

                newStore.StoreSections.Add(new StoreSection() { Name = "Deli", GroceryManagerUserId = userId });

                newStore.StoreSections.Add(new StoreSection() { Name = "Produce", GroceryManagerUserId = userId });

                context.Add(newStore);
                context.SaveChanges();
            }
            
            using (var context = new GroceryManagerContext())
            {
                // Attempting to eager load store sections.
                var stores = context.Stores
                   .Include(s => s.StoreSections)
                   .Where(s => s.GroceryManagerUserId == userId)
                   .ToList();

                Console.WriteLine($"The user guid is {userId}.");

                foreach (var store in stores)
                {
                    Console.WriteLine($"There are {store.StoreSections.Count} store sections in {store.Name}.");
                }
            }
        }

        public class Store
        {
            public int StoreId { get; set; }

            public string Name { get; set; } = string.Empty;

            public Guid GroceryManagerUserId { get; set; }

            public List<StoreSection> StoreSections { get; } = new List<StoreSection>();
        }

        public class StoreSection
        {
            public int StoreSectionId { get; set; }

            public string Name { get; set; } = string.Empty;

            public Guid GroceryManagerUserId { get; set; }

            public int StoreId { get; set; }
            public Store Store { get; set; } = new Store();
        }

        public class GroceryManagerContext : DbContext
        {
            public DbSet<Store>? Stores { get; set; }

            public DbSet<StoreSection>? StoreSections { get; set; }

            protected override void OnModelCreating(ModelBuilder builder)
            {
                if (builder == null)
                    throw new ArgumentNullException(nameof(builder));

                base.OnModelCreating(builder);

                builder.Entity<Store>()
                    .HasIndex(s => new { s.Name, s.GroceryManagerUserId })
                    .IsUnique();

                builder.Entity<StoreSection>()
                    .HasIndex(ss => new { ss.Name, ss.GroceryManagerUserId })
                    .IsUnique();

                builder.Entity<StoreSection>()
                    .HasOne(ss => ss.Store)
                    .WithMany(s => s.StoreSections)
                    .HasForeignKey(ss => new { ss.StoreId, ss.GroceryManagerUserId })
                    .HasPrincipalKey(s => new { s.StoreId, s.GroceryManagerUserId })
                    .IsRequired();
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlite(@"Data Source=D:\src\TestEfcore\TestEfcore\GroceryManager.db");
            }
        }
    }
}

StoreSections 導航屬性不是預先加載,因為您正在使用 new 運算符初始化 StoreSection 實體上的 Store 屬性。

這導致 StoreSection.StoreId 屬性被保存為 0,這會阻止創建關聯

您需要更改 StoreSection 實體以刪除初始化以解決問題:

public class StoreSection
{
    public int StoreSectionId { get; set; }

    public string Name { get; set; } = string.Empty;

    public Guid GroceryManagerUserId { get; set; }

    public int StoreId { get; set; }
    public Store Store { get; set; } // initialization has been removed here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM