簡體   English   中英

插入新實例時未執行實體框架核心延遲加載

[英]Entity framework core lazy loading not performed when inserting new instances

我有兩個班級:

  • 引用類客戶的Campaign

     public class Campaign { [Key] [Required] public int id { get; set; } public int? CustomerId { get; set; } [ForeignKey("CustomerId")] public virtual Customer customer { get; set; } }
  • 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

在對現有記錄執行提取操作時,延遲加載非常有效。

感謝

解決辦法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM