entity-framework - 为什么关系一对多给我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 的快速性能。如果自动包含所有子属性,则可能会在 EF 生成的 sql 查询中生成许多不必要的连接,这可能会对性能造成很大影响(如果是这种情况,我们可能会有一个.Exclude
扩展方法!)
IE:
List<Recipe> recipes = _applicationContext.Recipes.Include(x => x.Ingredients).Where(r => r.Category.ClientId == id).ToList();
推荐阅读
- angular - 在 d3 中以编程方式将指向特定节点的实线链接更改为虚线
- r - R使用cut.Date创建时间间隔
- tensorflow - Pretty Tensor 不适用于 Tensorflow 1.8
- spring - Thymeleaf 找不到国际化消息
- java - Mockito @SpyBean 注解与 SpringRunner 冲突
- php - 为 Codeception 启用 CURL
- matlab - MATLAB:如何解调 STREAMING 音频文件而不是保存的音频文件?
- python - 创建一个循环,为每行输出一个额外的空间
- arrays - Angular 6:通过httpClient从相应的JSON中获取对象数组
- r - 汇总值直到日期更改