我有两个类:
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
解决方案是:
使用
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;
}
关于c# - 插入新实例时不执行 Entity Framework 核心延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57179749/