[英]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
。
在對現有記錄執行提取操作時,延遲加載非常有效。
感謝戳
解決辦法是:
使用CreateProxy
為您的實體創建代理:
Campaign toCreate = _context.Campaigns.CreateProxy();
將新值傳輸到您的代理對象:
_context.Entry(toCreate).CurrentValues.SetValues(Campaign);
最后,將您的代理對象保存到上下文中:
_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.