问题描述
不确定我做错了什么。无论我做什么,我尝试遵循哪些帖子,我都无法使EF Eager加载正常工作。我不知道我之前是否做错了什么,但是没有任何效果。没有任何样式的包含,或禁用延迟加载...我只是无法获得它。
我有一个Agent模型
public class Agent
{
[Key]
public int AgentId { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; }
[Required]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[StringLength(100)]
public string LastName { get; set; }
然后是生产者模型
public class Producer
{
[Key]
public int ProducerId { get; set; }
[Required]
[StringLength(254)]
public string Name { get; set; }
public int StreetNumber { get; set; }
[StringLength(254)]
public string StreetName { get; set; }
[StringLength(254)]
public string City { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; }
public int CountryId { get; set; }
public virtual Country Country { get; set; }
然后我有另一个模型/表格来链接两者
public class AgentProducer
{
public int AgentProducerId { get; set; }
public int ProducerId { get; set; }
public int AgentId { get; set; }
public virtual Producer Producer { get; set; }
public virtual Agent Agent { get; set; }
}
这里的目标是,当我查询AgentProducer表时,我的Producer属性将具有整个生产者对象,而该生产者对象将具有Country和State对象。
我认为这无关紧要,但是生产者的countryId和stateId确实有FK约束
我的设置来自我正在上的一课,在那里我有一个存放所有内容的存储库包装程序
public class RepositoryContext : DbContext
{
public RepositoryContext(DbContextOptions<RepositoryContext> options) : base(options)
{
}
public DbSet<Producer> Producers { get; set; }
public DbSet<Agent> Agents { get; set; }
}
上面的项目保存在一个存储库包装中,该存储库具有一个存储库,该存储库为其中的每种模型类型实现了特定的接口。
我遇到的问题是我是使用方法语法还是LINQ进行查询,我无法使所有内容都包含在查询中,最终不得不做很多额外的步骤来获取某些信息。
到目前为止,与我最接近的是LINQ,在这种情况下,我将使AgentProducer项与Producer对象集一起返回-但是在该生产者内部,COuntry和State为空,因此我需要该信息。
我尝试过类似的事情: ***(值得一提的是,这里的“ AgentProducer”是一个DBSet ...不确定是否正确吗?我似乎没有在其他答案中看到的诸如“ ThenInclude”之类的选项。
_repoWrapper.Repo.AgentProducer.Include(i => i.Producer).Where(i => i.AgentId == filter.AgentId);
这甚至在没有引起我的国家/州问题之前,也没有给我任何收益-即使生产者为空。
我尝试过
var res = _repoWrapper.Repo.AgentProducer.Include("Producer").Where(i => i.AgentId == filter.AgentId);
相同的空结果。
(from ap in _repoWrapper.Repo.AgentProducer.Include(i => i.Producer)
where ap.AgentId == filter.AgentId
select ap);
相同的空值。
唯一无效的是:
var res = (from ap in _repoWrapper.Repo.AgentProducer
join p in _repoWrapper.Repo.Producers on ap.ProducerId equals p.ProducerId
join a in _repoWrapper.Repo.Agents on ap.AgentId equals a.AgentId
join c in _repoWrapper.Repo.Country on ap.Producer.Country.Name equals c.Name
join s in _repoWrapper.Repo.State on ap.Producer.State.Name equals s.Name
where ap.AgentId == filter.AgentId
orderby p.Name descending
select new AgentProducer
{
AgentProducerId = ap.AgentProducerId,Producer = p
});
由于手动连接并在对象上进行设置,从而填充了生产者。但是,A)确实不希望加载,并且B)使用这种方法我不知道如何在此处在生产者上设置国家和州对象,因为它们仍然显示为空。在对象初始化程序中,我不能只分配国家和州。
我浏览了无数种方法,我无法完成任何事情……所以我觉得我在此过程的早期做错了什么,但我不知道要做什么。
有人可以帮我吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)