Entity Framework Many to Many Can't get Related Data - c#

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; }
}

Related

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();

Multiple select query in linq c#

I have the following classes.
public class Candidate
{
public long Id { get; set; )
public List<JobAssigned> JobAssigned { get; set; }
}
public class JobAssigned
{
public long Id { get; set; }
public List<StageScore> StageScore { get; set; }
public List<CriteriaScore> CriteriaScore { get; set; }
public List<StageComment> StageComment { get; set; }
}
public class StageComment
{
public long Id { get; set; }
public JobAssigned JobAssigned { get; set; }
public long JobAssignedId { get; set; }
public long PipelineStageId { get; set; }
public long CandidateId { get; set; }
public long JobId { get; set; }
public string Comment { get; set; }
}
public class StageScore
{
public long Id { get; set; }
public JobAssigned JobAssigned { get; set; }
public long JobAssignedId { get; set; }
public long Rating { get; set; }
public long PipelineStageId { get; set; }
public long CandidateId { get; set; }
public long JobId { get; set; }
}
public class CriteriaScore
{
public long Id { get; set; }
public JobAssigned JobAssigned { get; set; }
public long JobAssignedId { get; set; }
public long Rating { get; set; }
public long PipelineStageCriteriaId { get; set; }
public long CandidateId { get; set; }
public long JobId { get; set; }
}
I want eager load all the related table at once. I was trying to the followning,
List<Candidate> candidate = _context.Candidates.
Include(f => f.JobAssigned.Select(g => g.StageScore))
.OrderBy(x => x.Id).ToList();
When I did .Select().Select() it was giving an error. How to get all the collections in a single query?
Look at this article I wrote, it loads all the objects dynamically.
And here is how you could include all objects.
I hope that there won't be circle references.
The plugin I wrote in the above url can handle circle references
List<Candidate> candidate = _context.Candidates.
Include(f => f.JobAssigned.Select(g => g.StageScore.Select(a=> a.JobAssigned))).
Include(f => f.JobAssigned.Select(g => g.CriteriaScore.Select(a=> a.JobAssigned))).
Include(f => f.JobAssigned.Select(g => g.StageComment.Select(a=> a.JobAssigned))).
OrderBy(x => x.Id).ToList();

Automapper 6.0.2.0, Mapper.Map() throws StackOverflow when mapping Child Entities

Getting straight to the point, I've got the following Models:
public abstract class ControlData
{
public DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
[ForeignKey("CreatedById")]
public Collaborator CreatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? UpdatedById { get; set; }
[ForeignKey("UpdatedById")]
public Collaborator UpdatedBy { get; set; }
}
[Table("My_Position_Table")]
public class Position : ControlData
{
[Key]
[Column("PositionId")]
public int Id { get; set; }
[Column("PositionStatusId")]
public int StatusId { get; set; }
[ForeignKey("StatusId")]
public PositionStatus Status { get; set; }
public int OpportunityId { get; set; }
[ForeignKey("OpportunityId")]
public Opportunity Opportunity { get; set; }
public int Total { get; set; }
[Column("PositionDurationId")]
public int DurationId { get; set; }
[ForeignKey("DurationId")]
public PositionDuration Duration { get; set; }
public DateTime StartDate { get; set; }
//TODO Agregar las otras propiedades con sus respectivos catalogos
public string PracticeId { get; set; }
[ForeignKey("PracticeId")]
public Practice Practice { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public PersonRole Role { get; set; }
public int PlatformId { get; set; }
[ForeignKey("PlatformId")]
public Platform Platform { get; set; }
public int LevelId { get; set; }
[ForeignKey("LevelId")]
public Level Level { get; set; }
public int EnglishLevelId { get; set; }
[ForeignKey("EnglishLevelId")]
public EnglishLevel EnglishLevel { get; set; }
public string CountryId { get; set; }
public int LocationId { get; set; }
[ForeignKey("LocationId")]
public Location Location { get; set; }
public int? OfficeId { get; set; }
public int OperationId { get; set; }
[ForeignKey("OperationId")]
public Person Operation { get; set; }
public int? EvaluatorId { get; set; }
[ForeignKey("EvaluatorId")]
public Collaborator Evaluator { get; set; }
public int? SourcerId { get; set; }
[ForeignKey("SourcerId")]
public Collaborator Sourcer { get; set; }
public List<Candidate> Candidates { get; set; }
public int? PositionCancellationReasonId { get; set; }
[ForeignKey("PositionCancellationReasonId")]
public PositionCancellationReason CancellationReason { get; set; }
public string CancellationComments { get; set; }
public int? CancellationById { get; set; }
[ForeignKey("CancellationById")]
public Collaborator CancellationBy { get; set; }
public DateTime? CancellationDate { get; set; }
public bool Active { get; set; }
public bool WhereAvailable { get; set; }
public bool RequestAsset { get; set; }
public string CityZone { get; set; }
public string TravelsTo { get; set; }
public string Description { get; set; }
public string SpecificationFile { get; set; }
public int PositionPriorityId { get; set; }
public int? SourcingGroupId { get; set; }
}
[Table("My_Opportunity_Table")]
public class Opportunity : ControlData
{
[Column("OpportunityId")]
[Key]
public int Id { get; set; }
[Column("OpportunityStatusId")]
public int StatusId { get; set; }
[ForeignKey("StatusId")]
public OpportunityStatus Status { get; set; }
public string ProjectId { get; set; }
[ForeignKey("ProjectId")]
public Project Project { get; set; }
public string MarketId { get; set; }
[ForeignKey("MarketId")]
public Market Market { get; set; }
public string CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
public string Name { get; set; }
[Column("OpportunityTypeId")]
public int TypeId { get; set; }
[ForeignKey("TypeId")]
public OpportunityType Type { get; set; }
[Column("OpportunityPriorityId")]
public int PriorityId { get; set; }
[ForeignKey("PriorityId")]
public OpportunityPriority Priority { get; set; }
public int? OpportunityCancellationReasonId { get; set; }
[ForeignKey("OpportunityCancellationReasonId")]
public OpportunityCancellationReason CancellationReason { get; set; }
public string CancellationComments { get; set; }
public int? CancellationById { get; set; }
[ForeignKey("CancellationById")]
public Collaborator CancellationBy { get; set; }
public DateTime? CancellationDate { get; set; }
public bool Active { get; set; }
public List<OpportunityRole> OpportunityRoles { get; set; }
public List<Position> Positions { get; set; }
}
And also, I've got their equivalents in DTO's:
public abstract class ControlDataDTO
{
public DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
public CollaboratorPlainDTO CreatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? UpdatedById { get; set; }
public CollaboratorPlainDTO UpdatedBy { get; set; }
}
public class PositionDTO: ControlDataDTO
{
public int Id { get; set; }
public int StatusId { get; set; }
public PositionStatusDTO Status { get; set; }
public int OpportunityId { get; set; }
public OpportunityDTO Opportunity { get; set; }
public int Total { get; set; }
public int DurationId { get; set; }
public PositionDurationDTO Duration { get; set; }
public DateTime StartDate { get; set; }
public string PracticeId { get; set; }
public PracticeDTO Practice { get; set; }
public int RoleId { get; set; }
public PersonRoleDTO Role { get; set; }
public int PlatformId { get; set; }
public PlatformDTO Platform { get; set; }
public int LevelId { get; set; }
public LevelDTO Level { get; set; }
public int EnglishLevelId { get; set; }
public EnglishLevelDTO EnglishLevel { get; set; }
public string CountryId { get; set; }
public int LocationId { get; set; }
public LocationDTO Location { get; set; }
public int? OfficeId { get; set; }
public int OperationId { get; set; }
public PersonDTO Operation { get; set; }
public string OperationIS { get; set; }
public bool WhereAvailable { get; set; }
public bool RequestAsset { get; set; }
public string CityZone { get; set; }
public string TravelsTo { get; set; }
public string Description { get; set; }
public int CandidatesAccepted { get; set; }
public int CandidatesRejected { get; set; }
public int CandidatesWaiting { get; set; }
public bool HasCandidatesWaiting { get; set; }
public int TotalCandidates { get; set; }
public string SpecificationFile { get; set; }
public int? EvaluatorId { get; set; }
public int? SourcerId { get; set; }
public CollaboratorDTO Sourcer { get; set; }
public int? SourcingGroupId { get; set; }
public PositionCancellationReasonDTO CancellationReason { get; set; }
}
public class OpportunityDTO: ControlDataDTO
{
public int Id { get; set; }
public int StatusId { get; set; }
public OpportunityStatusDTO Status { get; set; }
public string ProjectId { get; set; }
public ProjectDTO Project { get; set; }
public string MarketId { get; set; }
public MarketDTO Market { get; set; }
public string CustomerId { get; set; }
public CustomerDTO Customer { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public OpportunityTypeDTO Type { get; set; }
public int PriorityId { get; set; }
public OpportunityPriorityDTO Priority { get; set; }
public int? OpportunityCancellationReasonId { get; set; }
public OpportunityCancellationReasonDTO CancellationReason { get; set; }
public string CancellationComments { get; set; }
public int? CancellationById { get; set; }
public CollaboratorPlainDTO CancellationBy { get; set; }
public DateTime? CancellationDate { get; set; }
public CollaboratorDTO Responsible { get; set; }
public List<OpportunityRoleDTO> OpportunityRoles { get; set; }
public int TotalPositions { get; set; }
public bool CandidatesWarning { get; set; }
public bool Active { get; set; }
public List<PositionDTO> Positions { get; set; }
}
For this mapping initialization we are using Profiles, like this way:
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg =>
{
// ...
cfg.AddProfile<OpportunityMappingProfile>();
// ...
});
}
}
public class OpportunityMappingProfile : Profile
{
public OpportunityMappingProfile()
{
CreateMap<Opportunity, OpportunityDTO>()
.ForMember(x => x.Responsible, x => x.MapFrom(c => GetFromOpportunityRoles(c.OpportunityRoles, Constants.OpportunityResponsible)))
.ForMember(x => x.TotalPositions, x => x.MapFrom(c => c.Positions.Count()))
.ForMember(x => x.CandidatesWarning, x => x.MapFrom(c => c.Positions.Count() > 0 ?
c.Positions.Any(pos => pos.Candidates.Any(cand => cand.StatusId == 3)) :
false))
.ForMember(x => x.CreatedBy, x => x.MapFrom(c => Mapper.Map<CollaboratorPlainDTO>(c.CreatedBy)))
.ForMember(x => x.UpdatedBy, x => x.MapFrom(c => Mapper.Map<CollaboratorPlainDTO>(c.UpdatedBy)))
.ForMember(x => x.Positions, x => x.MapFrom(c => Mapper.Map<List<PositionDTO>>(c.Positions))).PreserveReferences(); --> Even using this method, StackOverflow exception is still occurring...
CreateMap<OpportunityDTO, Opportunity>()
.ForMember(x => x.CancellationReason, x => x.Ignore())
.ForMember(x => x.CreatedBy, x => x.Ignore())
.ForMember(x => x.UpdatedBy, x => x.Ignore())
.ForMember(x => x.Positions, x => x.Ignore());
}
private Collaborator GetFromOpportunityRoles(List<OpportunityRole> opportunityRoles, string rol)
{
var opportunityRole = opportunityRoles.FirstOrDefault(opp => opp.ProjectRoleTypeId == rol);
return opportunityRoles != null ? opportunityRole.Collaborator : null;
}
}
And finally, the logic that does the mapping where I'm getting the commented error...
public class OpportunityLogic : IOpportunityLogic
{
// Properties...
public OpportunityLogic(parameters list here, though irrelevant for this example)
{
// ...
}
public ActionResponse<List<OpportunityDTO>> GetOpportunitiesWithPositions(int personId)
{
// Information is retrieved from DB, here...
List<Opportunity> listOpportunities = opportunityRepository.Get(
opp => opp.Status,
opp => opp.Market,
opp => opp.Customer,
opp => opp.Type,
opp => opp.Project,
opp => opp.Status,
opp => opp.Positions,
opp => opp.Positions.Select(pos => pos.Candidates),
opp => opp.Positions.Select(pos => pos.Status),
opp => opp.Positions.Select(pos => pos.Practice),
opp => opp.Positions.Select(pos => pos.Role),
opp => opp.Positions.Select(pos => pos.Platform),
opp => opp.Positions.Select(pos => pos.Sourcer));
// After having retrieved data, here I re-define my model.
listOpportunities = listOpportunities
.Where( opp => opp.StatusId == (int)Constants.OpportunityStatus.Open &&
opp.Active == true &&
opp.Positions.Any(pos => pos.StatusId == (int)Constants.PositionStatus.Open &&
pos.Candidates.Any(can => can.PersonId == personId &&
can.Active == true &&
(can.StatusId == (int)Constants.CandidateStatus.Lead ||
can.StatusId == (int)Constants.CandidateStatus.Waiting))))
.ToList();
// MY PROBLEM IS HERE....
var mappedOpportunities = Mapper.Map<List<OpportunityDTO>>(listOpportunities);
return new ActionResponse<List<OpportunityDTO>> (mappedOpportunities);
}
}
My problem starts when trying to map my Model (List) to the DTO (List); the error is the well-known "StackOverflow Exception". If I'm using the "PreserveReferences()" method, why is still throwing the same exception?. The same goes for "MaxDepth() method", after having tried different depth levels (1,2,3...).
I've spent too many hours trying to solve this issue and to be honest, I'm out of ideas already. If anyone has an idea what to do here, I'll be really grateful.
Thanks and advance & regards!!
Starting from 6.1.0 PreserveReferences is set automatically at config time whenever the recursion can be detected statically. If that doesn't happen in your case, open an issue with a full repro and we'll look into it.
http://automapperdocs.readthedocs.io/en/latest/5.0-Upgrade-Guide.html#circular-references
But you have to remove the Map calls inside the MapFroms. Those ForMember-s are not needed.
The issue here is that I was missing another Mapping Profile that needed to preserve its references, but had not mentioned here, since I was missing that part and that was the one that had causing me all the issues.

Entity Framework is entering duplicate on bulk inserts approach

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();
}
}

Categories