插入新实例时不执行实体框架核心延迟加载

2024-02-13

我有两节课:

  • Campaign它引用了一个类客户:

    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, the customer不是延迟加载到插入的对象中。请注意,我尝试通过以下方式获取活动id在返回之前,但问题仍然存在,我想避免加载customer明确地。

在对现有记录执行提取操作时,延迟加载非常有效。


谢谢poke https://stackoverflow.com/users/216074/poke

解决办法是:

  1. 使用以下命令为您的实体创建代理CreateProxy https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.proxiesextensions.createproxy?view=efcore-2.1:

    Campaign toCreate = _context.Campaigns.CreateProxy();
    
  2. 将新值传输到您的代理对象:

    _context.Entry(toCreate).CurrentValues.SetValues(Campaign);
    
  3. 最后,将代理对象保存到上下文中:

    _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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

插入新实例时不执行实体框架核心延迟加载 的相关文章

随机推荐