首页 > 解决方案 > 为什么关系一对多给我null(实体框架)?

问题描述

我有以下应用程序数据库上下文:

public class ApplicationContext : DbContext
{
    private readonly string _connectionString;

    public ApplicationContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("Recipes");
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Recipe> Recipes { get; set; }
    public DbSet<Ingredient> Ingridients { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Ingredient>()
            .HasOne(x => x.Recipe)
            .WithMany(y => y.Ingredients);
    }
}

我的商业模式很简单:一份食谱有很多成分,而一种成分只有一张收据。

楷模

食谱:

public class Recipe
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public List<Ingredient> Ingredients { get; set; }

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }

    public Recipe()
    {
        CreatedAt = DateTime.UtcNow;
        UpdatedAt = DateTime.UtcNow;
    }
}

成分

public class Ingredient
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int ClientId { get; set; }

    public string Name { get; set; }

    public decimal Count { get; set; }

    public string Measure { get; set; }

    public int Number { get; set; }  

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }

    public Recipe Recipe { get; set; }

    public Ingredient()
    {
        CreatedAt = DateTime.UtcNow;
        UpdatedAt = DateTime.UtcNow;
    }
}

在这里,我试图从食谱中收集成分:

List<Recipe> recipes;


recipes = _applicationContext.Recipes.Where(r => r.Category.ClientId == id).ToList();

但是成分总是无效的。我不明白为什么。结果如下:

在此处输入图像描述

怎么了?

标签: entity-framework.net-core

解决方案


您需要在查询中包含子属性,否则您将从它们那里得到空值。这样做是为了保持 Entity Framework 的快速性能。如果自动包含所有子属性,则可能会在 EF 生成的 sql 查询中生成许多不必要的连接,这可能会对性能造成很大影响(如果是这种情况,我们可能会有一个.Exclude扩展方法!)

IE:

List<Recipe> recipes = _applicationContext.Recipes.Include(x => x.Ingredients).Where(r => r.Category.ClientId == id).ToList();


推荐阅读