【问题标题】:Lazy loading not working with 1 to 0 or 1 relationship延迟加载不适用于 1 到 0 或 1 关系
【发布时间】:2023-03-31 03:16:01
【问题描述】:

我有以下表格设计。

从这里可以看出,有一对多的关系,在 EpisodePatient 一方有很多。

然后,我有以下课程。

public class EpisodeModel
{
    public int ID { get; set; }
    public virtual EpisodePatientModel EpisodePatient { get; set; }
}
public class EpisodePatientModel
{
    public int EpisodePatientID { get; set; }
    public virtual EpisodeModel Episode { get; set; }
}

我在 Entity Framework 中将关系设置为一对 0 或多。这样做的原因是,我正在从视图中选择所有 EpisodePatients,并且我希望在访问时延迟加载该 Episode。

这就是我建立关系的方式。

modelBuilder.Entity<EpisodePatientModel>().HasRequired(r => r.Episode).WithOptional(o => o.EpisodePatient);

我希望它在我的代码中充当一对零或多,因为 Episode 将始终有一个 EpisodePatient,反之亦然。

我面临的问题是,当我加载 EpisodePatient 并尝试访问 Episode 链接项时,它始终为 null,并且不会发生延迟加载。

我在这里做错了什么?

更新

这就是我加载原始 EpisodePatient 项目的方式。

this.DbContext.EpisodePatients.AsNoTracking();

【问题讨论】:

  • 显示加载 EpisodePatient 的查询。
  • @mwisnicki 请看我的更新
  • 在标题中你提到了 1 到 0 或 1,但在细节中你说 有一对多的关系,在 EpisodePatient 方面有很多 ?如果是一对多,则必须将其更改为:public virtual ICollection&lt;EpisodePatientModel&gt; EpisodePatient { get; set; }
  • @Ziyad 问题是,在访问 EpisodeModel 时,我只想使用它链接到的当前 EpisodePatientModel,而不是使用 ICollection。这可以实现吗?

标签: c# asp.net-mvc entity-framework visual-studio relationship


【解决方案1】:

我重新创建了您的模型,但使用如下数据注释,它工作正常:

public class EpisodeModel
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual EpisodePatientModel EpisodePatient { get; set; }
}

public class EpisodePatientModel
{
    public string Name { get; set; }

    [Key, ForeignKey("Episode")]
    public int EpisodeId { get; set; }
    public virtual EpisodeModel Episode { get; set; }
}

【讨论】:

  • 我添加了 Title 和 Name 属性用于测试目的
  • 让我尝试一下 fluent API。我不确定您为什么将 EpisodeId 设置为 Key 和外键?
  • 因为关系是1-1或者1-0,所以只有主实体应该有自己的主键(id),而相关实体的主键就是主实体的主键。用 [Key, ForeignKey] 注释它,
【解决方案2】:

尝试不使用AsNoTracking(),因为如果您使用它,您的上下文将无法跟踪,并且您无法在需要时包含更多数据。

并尝试更改为一对多的关系。

modelBuilder.Entity<EpisodePatientModel>().HasRequired<Episode>(s => s.Episode).WithMany(s => s.EpisodePatient); 

【讨论】:

  • 尝试一对多关系,但仍然不使用'AsNoTracking()'。
猜你喜欢
  • 2021-02-28
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2020-11-22
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多