插入新实例时,Entity Framework Core不执行延迟加载。

7

我有两个类:

  • Campaign which references a class customer:

    public class Campaign
    {
        [Key]
        [Required]
        public int id { get; set; }
        public int? CustomerId { get; set; }
        [ForeignKey("CustomerId")]
        public virtual Customer customer { get; set; }
    }
    
  • And Customer:

    public class Customer
    {
        [Key]
        [Required]
        public int id { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public double turnover { get; set; }
        public virtual ICollection<Campaign> campaigns { get; set; }
    }
    

这是一个插入方法:

async Task<Campaign> ICampaignRepository.InsertCampaign(Campaign campaign)
{
    try
    {
        _context.Campaigns.Add(campaign);
        await _context.SaveChangesAsync();
        return campaign;
    }
    catch (Exception)
    {
        throw;
    }
}

我正在使用 Microsoft.EntityFrameworkCore.Proxies 包进行 延迟加载

在添加一个具有 customerId 的活动实例后,在插入的对象中不会惰性加载 customer。请注意,我尝试通过 id 获取活动,然后返回它,但问题仍然存在,并且我想避免显式加载 customer

当对现有记录执行提取操作时,延迟加载完美地工作。


EF Core默认情况下不会进行任何延迟加载(顺便说一句,这是件好事),我认为自动加载相关实体并不被支持。 - poke
我正在使用Microsoft.EntityFrameworkCore.Proxies包进行延迟加载。 - khalil
你传递给函数的实体很可能不是代理实体。因此,懒加载魔法不会在那里发生。你可能需要使用 _context.CreateProxy() 创建对象。 - poke
应该调用 _context.CreateProxy() 来创建父对象或导航属性吗? - khalil
你正在添加到上下文中的“活动”对象。 - poke
你能澄清一下如何使用 CreateProxy() 吗? - khalil
1个回答

10

感谢poke

解决方案如下:

  1. Create a proxy for your entity using CreateProxy:

    Campaign toCreate = _context.Campaigns.CreateProxy();
    
  2. Transfer new values to your proxy object:

    _context.Entry(toCreate).CurrentValues.SetValues(Campaign);
    
  3. Finally, save your proxy object to the context:

    _context.Add(toCreate);
    await _context.SaveChangesAsync();`
    
这里是完整的方法:
async Task<Campaign> ICampaignRepository.InsertCampaign(Campaign campaign)
{
    Campaign toCreate = _context.Campaigns.CreateProxy();
    _context.Entry(toCreate).CurrentValues.SetValues(campaign);
    _context.Add(toCreate);
    await _context.SaveChangesAsync();
    return toCreate;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接