Entity Framework is entering duplicate on bulk inserts approach - c#

I'm trying to use this reply https://stackoverflow.com/a/5942176/5741268 For bulk inserts. But this procedure is entering duplicate.
My Entities
public class Empresa
{
public int EmpresaId { get; set; }
public string CNPJ { get; set; }
public string CPF { get; set; }
public string IE { get; set; }
public string xNome { get; set; }
public string cMun { get; set; }
public string CNAE { get; set; }
//Endereço
public string COD_PAIS { get; set; }
public string UF { get; set; }
public string CEP { get; set; }
public string END { get; set; }
public string NUM { get; set; }
public string COMPL { get; set; }
public string BAIRRO { get; set; }
public string FONE { get; set; }
}
public class NFe
{
public int NFeId { get; set; }
//public int NFePartId { get; set; }
public string versao { get; set; }
public string chave { get; set; }
public string ide_mod { get; set; }
public string ide_serie { get; set; }
public string ide_nNF { get; set; }
public DateTime? ide_dEmi { get; set; }
public DateTime? ide_dSaiEnt { get; set; }
public string ide_tpNF { get; set; }
public decimal? TOTAIS_vBC { get; set; }
public decimal? TOTAIS_vICMS { get; set; }
public decimal? TOTAIS_vBCST { get; set; }
public decimal? TOTAIS_vST { get; set; }
public decimal? TOTAIS_vProd { get; set; }
public decimal? TOTAIS_vFrete { get; set; }
public decimal? TOTAIS_vSeg { get; set; }
public decimal? TOTAIS_vDesc { get; set; }
public decimal? TOTAIS_vII { get; set; }
public decimal? TOTAIS_vIPI { get; set; }
public decimal? TOTAIS_vPIS { get; set; }
public decimal? TOTAIS_vCOFINS { get; set; }
public decimal? TOTAIS_vOutro { get; set; }
public decimal? TOTAIS_vNF { get; set; }
public string infCpl { get; set; }
public bool cancelada { get; set; } = false;
public virtual NFePart NFePart { get; set; }
public virtual Empresa Empresa { get; set; }
public virtual ICollection<NFeItem> NFeItemLista { get; set; }
}
public class NFePart
{
public int NFePartId { get; set; }
public string NOME { get; set; }
public string COD_PAIS { get; set; }
public string CNPJ { get; set; }
public string IE { get; set; }
public string UF { get; set; }
public string CEP { get; set; }
public string END { get; set; }
public string NUM { get; set; }
public string COMPL { get; set; }
public string BAIRRO { get; set; }
public string COD_MUN { get; set; }
public string FONE { get; set; }
public virtual Empresa Empresa { get; set; }
public virtual ICollection<NFe> NFe { get; set; }
//Uso interno, não mapeado no banco de dados
[NotMapped]
public int COD_PART { get; set; }
}
Here is my code:
List<NFe> notas = new List<NFe>();
//populate notas
DataContext context = null;
try
{
List<Empresa> nEmpresas = notas.DistinctBy(x => new { x.Empresa.CNPJ }).Select(x => x.Empresa).ToList();
foreach (Empresa empresaToAdd in nEmpresas)
{
context = new DataContext();
context.Configuration.AutoDetectChangesEnabled = false;
int count = 0;
List<NFe> notasFilter;
notasFilter = notas.Where(x => x.Empresa.CNPJ == empresaToAdd.CNPJ).ToList();
int commitCount = 2000;
foreach (var notaInsert in notasFilter)
{
++count;
context = AddToContext(context, notaInsert, count, commitCount, true, notasFilter.Count);
}
}
}
finally
{
if (context != null)
context.Dispose();
}
My AddtoContext function
private static DataContext AddToContext(DataContext context, NFe entity, int count, int commitCount, bool recreateContext, int totalNfe)
{
//if has already inserted -> Attach entity.Empresa
if ((count > commitCount && commitCount != 0) || entity.Empresa.EmpresaId != 0)
{
context.Empresa.Attach(entity.Empresa);
}
if (context.NFePart.Any(p => p.CNPJ == entity.NFePart.CNPJ && p.Empresa.CNPJ == entity.Empresa.CNPJ))
{
context.NFePart.Attach(entity.NFePart);
}
context.Set<NFe>().Add(entity);
if (commitCount == 0 || count % commitCount == 0 || count == totalNfe)
{
context.SaveChanges();
if (recreateContext)
{
context.Dispose();
context = new DataContext();
context.Configuration.AutoDetectChangesEnabled = false;
}
}
return context;
}
After save changes, the EF insert duplicate
In the code I'm going through all have in "notas" and only filtering the "empresaToAdd" in question. but when the loop moves on to the next "empresaToAdd" it inserts again notes the previous company in the loop even using Dispose, and recreating the context
NFeItemMap
public class NFeItemMap : EntityTypeConfiguration<NFeItem>
{
public NFeItemMap()
{
ToTable("NFeItem");
HasKey(x => x.NFeItemId);
Property(x => x.infAdProd).HasColumnType("text").IsMaxLength();
//one-to-many
HasRequired(s => s.NFe)
.WithMany(s => s.NFeItemLista);
HasRequired(x => x.Empresa)
.WithMany();
}
}

Related

ASP.NET Core AutoMapper configuration error

I am trying to map an entity with a model but it's giving an error how can I check which property is causing the error?
Error: AutoMapper.AutoMapperMappingException: 'Error mapping types.'
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
This exception was originally thrown at this call stack:
AutoMapper.Mapper.MapCore<TSource, TDestination>(TSource, TDestination, AutoMapper.ResolutionContext, System.Type, System.Type, AutoMapper.MemberMap)
AutoMapper.Mapper.AutoMapper.IInternalRuntimeMapper.Map<TSource, TDestination>(TSource, TDestination, AutoMapper.ResolutionContext, System.Type, System.Type, AutoMapper.MemberMap)
AutoMapper.ResolutionContext.MapInternal<TSource, TDestination>(TSource, TDestination, AutoMapper.MemberMap)
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Account, AccountModel>();
CreateMap<AccountModel, Account>();
CreateMap<ServicePlan, ServicePlanModel>()
.ForMember(ServicePlanModel => ServicePlanModel.ServicePlanDetails, opt => opt.MapFrom(src => src.ServicePlanDetails.ToList()))
.ForMember(dest => dest.Lines, opt => opt.MapFrom(src => src.NLines ?? default))
.ForMember(dest => dest.StartDate, opt => opt.MapFrom(src => src.DateStart))
.ForMember(dest => dest.EndDate, opt => opt.MapFrom(src => src.DateEnd))
.ForMember(dest => dest.MonthlyCharges, opt => opt.MapFrom(src => src.AmountMonthly))
.ForMember(dest => dest.OneTimeCharges, opt => opt.MapFrom(src => src.AmountOnetime));
}
}
public async Task<List<ServicePlanModel>> GetServicePlansWithDetails(long accountId)
{
var plan = mapper.Map<ServicePlan, ServicePlanModel>(servicePlan);
}
public partial class ServicePlan
{
public ServicePlan()
{
ServicePlanDetails = new HashSet<ServicePlanDetail>();
}
public long PlanId { get; set; }
public decimal PhoneId { get; set; }
public byte? NLines { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public decimal? AmountMonthly { get; set; }
public decimal? AmountOnetime { get; set; }
public string? ContractType { get; set; }
public string? CallerId { get; set; }
public bool? Active { get; set; }
public short? ResellerId { get; set; }
public int? OnetimeInvoiceNo { get; set; }
public bool? IsRequest { get; set; }
public string? RequestType { get; set; }
public string? NewValue { get; set; }
public DateTime? RequestDate { get; set; }
public string? RequestBy { get; set; }
public bool? IsRejected { get; set; }
public bool? IsApproved { get; set; }
public DateTime? ApprovedWhen { get; set; }
public string? ApprovedBy { get; set; }
public string? Comments { get; set; }
public string? AdditionalDetails { get; set; }
public string? VideoTronId { get; set; }
public string? Zone { get; set; }
public string? PrevProvider { get; set; }
public bool? Charge911Tax { get; set; }
public string? ContractTerms { get; set; }
public long? ContractId { get; set; }
public int AllowedBandwidth { get; set; }
public DateTime? ServiceStartDate { get; set; }
public string? AppointmentTime { get; set; }
public DateTime? AppointmentEmailSentOn { get; set; }
public string? TrackingNumber { get; set; }
public bool? HasNumberPort { get; set; }
public DateTime? EstPortDate { get; set; }
public DateTime? PortCompletedOn { get; set; }
public bool? IsExGbchargesLimited { get; set; }
public decimal? ExGbchagesLimitAmt { get; set; }
public bool? IsPreVisitSch { get; set; }
public DateTime? PreVisitSchDate { get; set; }
public string? PreVisitSchTime { get; set; }
public bool? MoniterBwUsage { get; set; }
public int? BwWarnLimit { get; set; }
public string? DslaccountId { get; set; }
public string? BellGisId { get; set; }
public string? DslPassword { get; set; }
public bool? IsPasswordPassed { get; set; }
public bool? IsDslUserPassed { get; set; }
public string? CogecoId { get; set; }
public int? ServiceProviderId { get; set; }
public string? RogersId { get; set; }
public decimal? InternetSpeed { get; set; }
public bool? ModemRental { get; set; }
public bool? RouterRental { get; set; }
public bool? Atarental { get; set; }
public string? DslaccountDomain { get; set; }
[NotMapped]
public virtual ICollection<ServicePlanDetail> ServicePlanDetails { get; set; }
}
public class ServicePlanModel
{
public ServicePlanModel()
{
ServicePlanDiscounts = new List<ServicePlanDiscount>();
ServicePlanDetails = new List<ServicePlanDetail>();
}
[Key]
public Int64 PlanId { get; set; }
public Int64? ContractId { get; set; }
public int ResellerId { get; set; }
public Int64 PhoneId { get; set; }
public bool IsPhone { get; set; }
public Int32? OneTimeInvoiceId { get; set; }
public UInt16 Lines { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public Decimal MonthlyCharges { get; set; }
public Decimal OneTimeCharges { get; set; }
public String ContractType { get; set; }
public String CallerId { get; set; }
public Boolean IsActive { get; set; }
public Boolean IsRequest { get; set; }
public Boolean IsRejected { get; set; }
public Boolean IsApproved { get; set; }
public Boolean Charge911Tax { get; set; }
public DateTime ApprovedOn { get; set; }
public String ApprovedBy { get; set; }
public String Comments { get; set; }
public String ContractTerms { get; set; }
public String AdditionalDetails { get; set; }
public String VideoTronId { get; set; }
public String Zone { get; set; }
public String PreviousProvider { get; set; }
public String RequestType { get; set; }
public String NewValue { get; set; }
public DateTime? RequestDate { get; set; }
public String RequestedBy { get; set; }
//public PhoneNumber PhoneNumber { get; set; }
public List<ServicePlanDetail> ServicePlanDetails { get; set; }
public List<ServicePlanDiscount> ServicePlanDiscounts { get; set; }
public bool IsLandLinePlan
{
get
{
if (ServicePlanDetails != null)
{
return ServicePlanDetails.Any(spd => new String[] { "landline-r", "landline-b", "plan_10103", "plan_10104", "plan_10105" }.Contains(spd.ServiceCode));
}
return false;
}
}
public String ServicePlanName
{
get
{
if (ServicePlanDetails != null && ServicePlanDetails.Count > 0)
{
var plan = ServicePlanDetails.SingleOrDefault(spd => spd.IsPlan);
if (plan != null)
{
if (IsPhone)
{
return String.Format("{0} ({3}) ({1} x {2})", plan.ServiceTitle, plan.UnitPrice.ToString("N2"), plan.Quantity, PhoneId.ToString("###-###-####"));
}
return String.Format("{0} ({1} x {2})", plan.ServiceTitle, plan.UnitPrice.ToString("N2"), plan.Quantity);
}
}
return String.Empty;
}
}
public String MonthlyChargesDetails
{
get
{
if (ServicePlanDetails != null && ServicePlanDetails.Count > 0)
{
var items = ServicePlanDetails.Where(spd => spd.IsPlan == false & spd.UnitPrice > 0 & spd.ServiceType.Equals(Constants.SERVICE_TYPE_MONTHLY)).ToList();
var details = new StringBuilder();
foreach (var spd in items)
{
details.Append(String.Format("{0} ({1} x {2}) ", spd.ServiceTitle, spd.UnitPrice.ToString("N2"),
spd.Quantity));
}
return details.ToString();
}
return String.Empty;
}
}
//public String OnetimeChargesDetails
//{
// get
// {
// if (ServicePlanDetails != null && ServicePlanDetails.Count > 0)
// {
// var items = ServicePlanDetails.Where(spd => spd.IsPlan == false & spd.UnitPrice > 0 & spd.ServiceType.Equals(Constants.SERVICE_TYPE_ONETIME)).ToList();
// var details = new StringBuilder();
// foreach (var spd in items)
// {
// details.Append(String.Format("{0} ({1} x {2}) ", spd.ServiceTitle, spd.UnitPrice.ToString("N2"),
// spd.Quantity));
// }
// return details.ToString();
// }
// return String.Empty;
// }
//}
public List<ServicePlanDetail> OnetimeChargesDetails
{
get
{
if (ServicePlanDetails != null && ServicePlanDetails.Count > 0)
{
return ServicePlanDetails.Where(spd => spd.IsPlan == false & spd.ServiceType.Equals(Constants.SERVICE_TYPE_ONETIME)).ToList();
}
return null;
}
}
public List<ServicePlanDetail> FreeServicesDetails
{
get { return ServicePlanDetails != null ? ServicePlanDetails.Where(s => s.UnitPrice == 0 && !s.ServiceType.Equals("month")).ToList() : null; }
}
public List<ServicePlanDetail> DiscountedServicesDetail
{
get
{
return ServicePlanDetails != null ?
ServicePlanDetails.Where(s => s.ResellerService != null && s.UnitPrice < s.ResellerService.SuggestedPrice && !s.ServiceType.Equals("month")).ToList() : null;
}
}
public string Modem_MAC { get; set; }
public string TrackingNumber { get; set; }
}
I tried debugging but could not find the error.
Take a look at the source for AutoMapperMappingException. There are a number of properties on the exception that can be examined while under a debugger.
From the source...
public TypePair? Types { get; set; }
public TypeMap TypeMap { get; set; }
public MemberMap MemberMap { get; set; }
These properties are used to create the string for the Message property.
If for some reason that doesn't give you enough information, a way more intensive and semi-destructive way (have a backup of your source) is to cut half of the properties from the source/target types and see if the error still occurs. If yes, cut in half again, if no take the other properties and try again.
Basically, you are doing a binary search to narrow down the problem until it becomes obvious.

Entity Framework 6.1: update child ICollection when the parent entity is created

I have to pass some data from a source DB to another target DB both handled using Entity Framework just with two different DbContexts.
This is my code:
internal async static Task UploadNewsList(DateTime dataStart, TextWriter logger)
{
try
{
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
using (BDContentsDataModel buffettiContext = new BDContentsDataModel())
{
List<News> newsList = buffettiContext.News.Where(x => x.Online && x.DataPub >= dataStart.Date).ToList();
using (DirectioDBContext directioContext = new DirectioDBContext())
{
foreach(News buffettiNews in newsList)
{
bool hasAuth = false;
List<DirectioAutore> listAutori = null;
List<DirectioAutore> listAutoriFinal = new List<DirectioAutore>();
if (buffettiNews.AutoreList?.Count > 0)
{
hasAuth = true;
listAutori = EntitiesHelper.GetAutoriDirectio(buffettiNews.AutoreList.ToList(), directioContext);
foreach (var autore in listAutori)
{
int dirAuthId = 0;
bool exist = false;
foreach (var dirAut in directioContext.Autori)
{
if (dirAut.Nome.IndexOf(autore.Nome, StringComparison.InvariantCultureIgnoreCase) >= 0 &&
dirAut.Cognome.IndexOf(autore.Cognome, StringComparison.InvariantCultureIgnoreCase) >= 0)
{
exist = true;
dirAuthId = dirAut.Id;
}
}
//directioContext.Autori.
//Where(x => autore.Cognome.ToLowerInvariant().Contains(x.Cognome.ToLowerInvariant()) &&
// autore.Nome.ToLowerInvariant().Contains(x.Nome.ToLowerInvariant())).Any();
if (!exist)
{
directioContext.Autori.Add(autore);
directioContext.SaveChanges();
}
else
{
autore.Id = dirAuthId;
}
listAutoriFinal.Add(autore);
}
}
DirectioNews directioNews = EntitiesHelper.CreateDirectioNewsModel(buffettiNews);
if (hasAuth)
directioNews.AutoreList = listAutoriFinal;
if (directioNews == null)
throw new Exception("[News] - Trasformazione entità fallita");
directioContext.News.Add(directioNews);
await directioContext.SaveChangesAsync();
}
}
}
}
catch (Exception ex)
{
logger.WriteLine(ex.Message);
throw ex;
}
}
This is the target DbContext:
public class DirectioDBContext : DbContext
{
public DirectioDBContext() : base("name=DirectioCMSDataModel") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// ...
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("Autore_Id");
cs.MapRightKey("News_Id");
cs.ToTable("NewsAutore");
});
}
public virtual DbSet<DirectioNews> News { get; set; }
public virtual DbSet<DirectioVideo> Video { get; set; }
public virtual DbSet<DirectioMedia> Media { get; set; }
public virtual DbSet<DirectioAutore> Autori { get; set; }
public virtual DbSet<DirectioVideoAutori> VideoAutori { get; set; }
}
This is the interested target Parent Model:
[Table("News")]
public partial class DirectioNews
{
[Key]
public int Id { get; set; }
public string Titolo { get; set; }
public int IdDocType { get; set; }
public string Abstract { get; set; }
public string Testo { get; set; }
[Required]
public DateTime DataPub { get; set; }
public int IdUmbraco { get; set; }
public int CreatedById { get; set; }
public DateTime CreateDate { get; set; }
public int? UpdateById { get; set; }
public DateTime? UpdateDate { get; set; }
public int? DeletedById { get; set; }
public DateTime? DeletedDate { get; set; }
public int? ResumedById { get; set; }
public DateTime? ResumedDate { get; set; }
public int? PublishedById { get; set; }
public DateTime? PublishedDate { get; set; }
public int? UnpublishedById { get; set; }
public DateTime? UnpublishedDate { get; set; }
public DateTime? PublishedFrom { get; set; }
public DateTime? PublishedTo { get; set; }
public bool Online { get; set; }
public bool APagamento { get; set; }
public int IdConsulenzaOld { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<DirectioAutore> AutoreList { get; set; }
public bool IsFromOtherCMS { get; set; } = false;
public string Name { get; set; }
public int? NodeId { get; set; }
public int SortOrder { get; set; } = 0;
public Guid PlatformGuid { get; set; }
public Guid SourceGuid { get; set; }
// Permette l'accesso anche senza login
public bool FreeWithoutLogin { get; set; }
// nasconde dalla visualizzazione della lista normale del frontend, visibile solo attraverso l'etichetta campagna
public bool HideFromList { get; set; }
#region parametri per riferimenti temporali
public int? Day { get; set; } = null;
public int? Month { get; set; } = null;
public int? Year { get; set; } = null;
#endregion
public int? MediaId
{
get; set;
}
}
And this is the target Child model
[Table("Autori")]
public class DirectioAutore
{
[Key]
public int Id { get; set; }
public string Nome { get; set; }
[Required]
public string Cognome { get; set; }
public string DescrizioneBreve { get; set; }
public string Descrizione { get; set; }
public string Email { get; set; }
public string Immagine { get; set; }
public string Tipo { get; set; } // Maschio Femmina Team
public string Twitter { get; set; }
public int IdUmbraco { get; set; }
public bool Online { get; set; }
public DateTime? PublishedFrom { get; set; }
public DateTime? PublishedTo { get; set; }
public int IdOld { get; set; }
public bool IsDeleted { get; set; }
public int? NodeId { get; set; }
public string Name { get; set; }
public int CreatedById { get; set; } = 1;
public DateTime CreateDate { get; set; }
public int? UpdateById { get; set; }
public DateTime? UpdateDate { get; set; }
public int? DeletedById { get; set; }
public DateTime? DeletedDate { get; set; }
public int? ResumedById { get; set; }
public DateTime? ResumedDate { get; set; }
public int? PublishedById { get; set; }
public DateTime? PublishedDate { get; set; }
public int? UnpublishedById { get; set; }
public DateTime? UnpublishedDate { get; set; }
public string MetaaDescrBreve { get; set; }
public int? MediaId
{
get; set;
}
public Guid PlatformGuid { get; set; }
public Guid SourceGuid { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public virtual ICollection<DirectioNews> News { get; set; }
}
EntityFramework generated this table to handle this many-to-many relation:
When it saves the entity, it goes into the catch statement and show this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.NewsAutore_dbo.Autori_Autore_Id". The conflict occurred in database "DirectioContentsCMS_Stage_20201102", table "dbo.Autori", column 'Id'
What could be the problem?
Thank you so much
[SOLVED]
I was wrongly pointing LeftKey and RightKey into the DbContext, they was not pointing to the correct FKs.
I just inverted FKs:
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("Autore_Id");
cs.MapRightKey("News_Id");
cs.ToTable("NewsAutore");
});
instead of
modelBuilder.Entity<DirectioNews>()
.HasMany(s => s.AutoreList)
.WithMany(x => x.News)
.Map(cs =>
{
cs.MapLeftKey("News_Id");
cs.MapRightKey("Autore_Id");
cs.ToTable("NewsAutore");
});
Because MapLeftKey points to the parent entity of the navigation property specified in the HasMany method and MapRightKey points to the parent entity of the navigation property specified in the WithMany. I was doing exactly the opposite.
Then i moved the association after actually saving the news to prevent multiple authors creation:
// ...
DirectioNews directioNews = EntitiesHelper.CreateDirectioNewsModel(buffettiNews);
if (directioNews == null)
throw new Exception("[News] - Trasformazione entità fallita");
directioContext.News.Add(directioNews);
directioContext.SaveChanges();
if (hasAuth)
{
List<int> ids = listAutori.Select(s => s.Id).ToList();
List<DirectioAutore> r = directioContext.Autori.Where(x => ids.Contains(x.Id)).ToList();
directioNews.AutoreList = r;
directioContext.SaveChanges();
}

Including foreign key values into a DTO for a single record

It's been a while since I have done this, but I know there is an easy way to do this that I have forgotten. Below I have a class designed to populate a single record of a data object. But I cannot get the values from another table (related by foreign key) to populate using the lambda statement because I am missing something (the two values being pulled in from another table below can be seen as dto.LeaseName and dto.CarName). How should I write the lambda for the object dm?
public StationUnloadingLogDTO GetSingleRecordforLog(int Id)
{
StationUnloadingLogDTO dto = new StationUnloadingLogDTO();
StationUnloadingLog dm = new StationUnloadingLog();
dm = entity.StationUnloadingLog
.Where(x => x.Id == Id)
.FirstOrDefault();
dto.Id = dm.Id;
dto.DateLogged = dm.DateLogged;
dto.DriverName = dm.DriverName;
dto.TruckNumber = dm.TruckNumber;
dto.CarName = dm.Carrier.CarName;
dto.CarrierId = dm.CarrierId;
dto.SpecificGravity = dm.SpecificGravity;
dto.LactMeterOpen = dm.LactMeterOpen;
dto.LactMeterClose = dm.LactMeterClose;
dto.EstimatedBarrels = dm.EstimatedBarrels;
dto.TicketNumber = dm.TicketNumber;
dto.LeaseNumber = dm.LeaseNumber;
dto.LeaseName = dm.Company.CmpName;
dto.StationId = dm.StationId;
return dto;
}
Here are the related data classes
namespace Data.Models
{
public partial class Company
{
public Company()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CmpId { get; set; }
public string CmpName { get; set; }
public string CmpAddress1 { get; set; }
public string CmpAddress2 { get; set; }
public int? CmpCity { get; set; }
public string CmpZip { get; set; }
public string CmpPrimaryphone { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
public class StationUnloadingLogDTO
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public string CarName { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseName { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
}
public partial class StationUnloadingLog
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
public Carrier Carrier { get; set; }
public Company Company { get; set; }
public Tractorprofile Tractorprofile { get; set; }
}
public partial class Carrier
{
public Carrier()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CarId { get; set; }
public string CarName { get; set; }
public string CarAddress1 { get; set; }
public string CarAddress2 { get; set; }
public int? CtyCode { get; set; }
public string CarZip { get; set; }
public string CarContact { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
You should query for your record with child entities like this.
dm = DbSet<StationUnloadingLog>
.Where(x => x.Id == Id).Include(x => x.Carrrier)
.FirstOrDefault();

Getting Stackoverflow exception when mapping using automapper

I am getting StackOverflow exception while passing the objects using automapper.
This is before mapping getting result accurately
Here is the error where exception comes when mapping
My Domain Model class is
public class Appointment
{
[Key]
public int AppointmentID { get; set; }
public int Serial { get; set; }
public int AppointmentTypeID { get; set; } = 2;
public DateTime CreatedAt { get; set; }
public string CreatedBy { get; set; }
public DateTime? UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
[ForeignKey("CreatedBy")]
public virtual User User { get; set; }
public virtual ICollection<VisitRequest> VisitRequests { get; set; }
[ForeignKey("AppointmentTypeID")]
public virtual VisitPurpose VisitPurpose { get; set; }
public virtual ICollection<AppointmentStatus> AppointmentStatuses { get; set; }
}
My View Model Classes are
public class ApproveAppointmentViewModel
{
[Key]
public int AppointmentID { get; set; }
public int Serial { get; set; }
public int AppointmentTypeID { get; set; }
public virtual ICollection<ApproveAppointmentVisitRequestViewModel> VisitRequests { get; set; }
public virtual ICollection<ApproveAppointmentStatusViewModel> AppointmentStatuses { get; set; }
}
public class ApproveAppointmentVisitRequestViewModel
{
[Key]
public int VisitRequestID { get; set; }
public bool SendSMS { get; set; }
public int? PurposeID { get; set; }
public string PurposeDescription { get; set; }
public string Attachment { get; set; }
public int VisitorID { get; set; }
public int? AppointmentID { get; set; }
public virtual ApproveAppointmentViewModel Appointment { get; set; }
public virtual ApproveAppointmentVisitorViewModel Visitor { get; set; }
}
public class ApproveAppointmentVisitorViewModel
{
[Key]
public int? VisitorID { get; set; }
public string NationalID { get; set; }
public string FullName { get; set; }
public int Gender { get; set; }
public string Job { get; set; }
public string Type { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public virtual ICollection<ApproveAppointmentVisitRequestViewModel> VisitRequests { get; set; }
}
public class ApproveAppointmentStatusViewModel
{
public int StatusID { get; set; }
public int AppointmentID { get; set; }
public int StatusCode
{
get
{
return 1;
}
}
public DateTime ValidFrom
{
get
{
return DateTime.UtcNow.AddHours(3);
}
}
[UnavailableDate]
public DateTime? AppointmentDateTime
{
get
{
if (AppointmentDate != null)
{
if (AppointmentTime != null && AppointmentTime.Length > 0)
return new DateTime(AppointmentDate.Value.Year, AppointmentDate.Value.Month, AppointmentDate.Value.Day, int.Parse(AppointmentTime.Split(':')[0]), int.Parse(AppointmentTime.Split(':')[1]), 0);
else
return new DateTime(AppointmentDate.Value.Year, AppointmentDate.Value.Month, AppointmentDate.Value.Day);
}
else
{
return null;
}
}
}
public DateTime? AppointmentDate { get; set; }
public DateTime? _AppointmentDate { get; set; }
[Display(Name = "التاريخ")]
public string AppointmentDateHijri
{
get
{
if (AppointmentDate.HasValue)
return AppointmentDate.Value.ConvertToHijriString();
return null;
}
set
{
if (value != null)
{
var generalDate = new DateTime(int.Parse(value.Split('/')[0]), int.Parse(value.Split('/')[1]), int.Parse(value.Split('/')[2]));
AppointmentDate = generalDate.Year > 1500 ? generalDate : generalDate.ConvertToGeorgian();
}
else
AppointmentDate = null;
}
}
[Display(Name = "ملاحظة الإعتماد")]
public string StatusNote { get; set; }
[Required(ErrorMessage = "يجب تحديد الوقت المعتمد")]
[Display(Name = "الوقت")]
public string AppointmentTime { get; set; }
[Range(0, 60, ErrorMessage = "أقل مدة للزيارة 10 دقائق واقصى مدة 60 أو مفتوح")]
[Display(Name = "المدة (دقائق)")]
public int? AppointmentDuration { get; set; }
public virtual ApproveAppointmentViewModel Appointment { get; set; }
}
Controller code is
var AppointmentRequest = db.Appointments.Where(p => p.AppointmentID == id).Include(m => m.VisitRequests).Include(m => m.AppointmentStatuses).FirstOrDefault();
here i am getting exception when mapping using automapper
var vmodel = Mapper.Map<ApproveAppointmentViewModel>(AppointmentRequest);

Entity Framework Many to Many Can't get Related Data

Trying to get Collection from Many to many table with no luck.
currently have 3 tables. I'm not sure how to get to the SkillPool_lookup.skillname for each job.
I currently have.
using(Entities dbCtx = new Entities())
{
this.JobList = dbCtx.Jobs.Where(x => x.JobStatusId == 1)
.Include(x => x.JobStatus_Lookup)
.Include(x => x.Budget_Lookup)
.Include(x => x.JobCategories_Lookup)
.Include(x => x.JobType_Lookup)
.Include(x => x.Job_SubCategories_Lookup)
.Include(x => x.TimeLine_Lookup)
.Include(x => x.RequiredJobSkills)
.OrderByDescending(x => x.DateCreated)
.ToList();
}
but Requirejobskills.skillpool_lookup always null??? stuck. please help.
public Job()
{
this.RequiredJobSkills = new HashSet<RequiredJobSkill>();
this.JobReporteds = new HashSet<JobReported>();
this.JobsEmaileds = new HashSet<JobsEmailed>();
this.JobsSaveds = new HashSet<JobsSaved>();
}
public int Id { get; set; }
public string Description { get; set; }
public string UserId { get; set; }
public int QuoteCount { get; set; }
public int BudgetAmountId { get; set; }
public int MaxBidCount { get; set; }
public int JobCategoryId { get; set; }
public int JobStatusId { get; set; }
public System.DateTime DateCreated { get; set; }
public int JobCategorySubCatId { get; set; }
public int JobTypeId { get; set; }
public string Title { get; set; }
public int QuoteCountryOfOrginId { get; set; }
public Nullable<System.DateTime> DateFilled { get; set; }
public Nullable<System.DateTime> DateCanceled { get; set; }
public Nullable<System.DateTime> DateCompleted { get; set; }
public int TimeLineId { get; set; }
public Nullable<System.Guid> UserIdentifier { get; set; }
public System.Guid JobIdentifier { get; set; }
public Nullable<int> UnseenQuotesCount { get; set; }
public Nullable<int> UnseenMessagesCount { get; set; }
public Budget_Lookup Budget_Lookup { get; set; }
public Job_SubCategories_Lookup Job_SubCategories_Lookup { get; set; }
public JobCategories_Lookup JobCategories_Lookup { get; set; }
public JobStatus_Lookup JobStatus_Lookup { get; set; }
public JobType_Lookup JobType_Lookup { get; set; }
public TimeLine_Lookup TimeLine_Lookup { get; set; }
public ICollection<RequiredJobSkill> RequiredJobSkills { get; set; }
public ICollection<JobReported> JobReporteds { get; set; }
public ICollection<JobsEmailed> JobsEmaileds { get; set; }
public ICollection<JobsSaved> JobsSaveds { get; set; }
}
public partial class RequiredJobSkill
{
public int Id { get; set; }
public int SkillId { get; set; }
public int JobId { get; set; }
public Job Job { get; set; }
public SkillPool_lookup SkillPool_lookup { get; set; }
}
public partial class SkillPool_lookup
{
public SkillPool_lookup()
{
this.UserSkills = new HashSet<UserSkill>();
this.RequiredJobSkills = new HashSet<RequiredJobSkill>();
}
public int Id { get; set; }
public string SkillName { get; set; }
public string Description { get; set; }
public ICollection<UserSkill> UserSkills { get; set; }
public ICollection<RequiredJobSkill> RequiredJobSkills { get; set; }
}

Categories