Entity framework 插入新实例时未执行核心延迟加载
Entity framework core lazy loading not performed when inserting new instances
我有两个 classes:
Campaign
引用 class 客户:
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
。
延迟加载在对现有记录执行提取操作时非常有效。
感谢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;
}
我有两个 classes:
Campaign
引用 class 客户: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
。
延迟加载在对现有记录执行提取操作时非常有效。
感谢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;
}