I have two classes:
Campaignwhich references a class customer:public class Campaign { [Key] [Required] public int id { get; set; } public int? CustomerId { get; set; } [ForeignKey("CustomerId")] public virtual Customer customer { get; set; } }And
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; } }
Here's is an insert method:
async Task<Campaign> ICampaignRepository.InsertCampaign(Campaign campaign)
{
try
{
_context.Campaigns.Add(campaign);
await _context.SaveChangesAsync();
return campaign;
}
catch (Exception)
{
throw;
}
}
I'm using Microsoft.EntityFrameworkCore.Proxies package for lazy loading.
After adding a campaign instance having a customerId, the customer is not lazy loaded in the inserted object. Please note that I tried to fetch the campaign by id before returning it, but the problem persists, and I want to avoid loading the customer explicitly.
Lazy loading is perfectly working when performing fetch operations on existing records.
_context.CreateProxy()._context.CreateProxy()should be called to create the parent object or the navigation property ?Campaignobject that you are adding to the context.