c# - 插入新实例时不执行 Entity Framework 核心延迟加载

标签 c# .net-core entity-framework-core lazy-loading

我有两个类:

  • Campaign 引用类客户:

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

    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

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

最佳答案

感谢poke

解决方案是:

  1. 使用 CreateProxy 为您的实体创建代理:

    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;
}

关于c# - 插入新实例时不执行 Entity Framework 核心延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57179749/

相关文章:

C#惰性执行+内存理解

c# - 更改时间跨度毫秒分隔符;逗号 (,) 而不是点 (.)

c# - 有没有办法在调试时查看 UI 更新?

具有 Entity Framework Core 2.0 和 .NET 4.7 的 Azure 函数

linq - Linq 查询中的缓存结果

c# - 使用包含与 ThenInclude

c# - 在使用 [Import(AllowDefault = true)] 之前未调用 MEF [ImportingConstructor]

Azure函数v2,核心3.1无法加载文件或程序集System.Memory,版本= 4.2.0.0

asp.net-core - 如何将 AspNetCore 从 2.2.0 更新到 2.2.2

sql-server - 同一服务器上的两个 DbContext 抛出 : This platform does not support distributed transactions