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);
Related
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();
}
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();
I am trying to map multiple Userprofile models into a single viewModel. At a time only one user data will be mapped.
In the below code snippet I mentioned the use case that I already tried.
Also, I try to AutoMapper.Map<source,target> but didn't work for me.
//This is one FarmerUser Model
public partial class FarmerProfileModel
{
public long FarmerId { get; set; }
public string FarmerName { get; set; }
public string FatherHusbandName { get; set; }
public string Cnic { get; set; }
public string Gender { get; set; }
public string CellPhone { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateCellPhoneNo { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string FarmerImage { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public Guid? UserGuid { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Another Model of the Tso User
public class TsoProfileModel
{
public long Tsoid { get; set; }
public string Tsoname { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string Tsoimage { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public TbDistrictCode DistrictCodeNavigation { get; set; }
public TbTehsilCode TehsilCodeNavigation { get; set; }
}
This is my ViewModel in which i am trying to incorporrate my data of Farmer/Tso
public class UserProfileInfo
{
public long? UserId { get; set; }
public string UserName { get; set; }
public string Cnic { get; set; }
public string Email { get; set; }
public string AlternateCellPhone { get; set; }
public string Landline { get; set; }
public string Gender { get; set; }
public string PresentAddress { get; set; }
public string PermanentAddress { get; set; }
public int? EducationCode { get; set; }
public string image { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InsertionDate { get; set; }
public string ActiveStatus { get; set; }
public Guid? UserGuid { get; set; }
public string FatherHusbandName { get; set; }
public string CellPhone { get; set; }
public int? MaleDependant { get; set; }
public int? FemaleDependant { get; set; }
public string AlternateName { get; set; }
public string AlternateRelationshipwithFarmer { get; set; }
public int? ReferalCode { get; set; }
public string UnionCouncil { get; set; }
public string MozaName { get; set; }
public int? SmallAnimals { get; set; }
public int? BigAnimals { get; set; }
public int? Tractor { get; set; }
public string Role { get; set; }
public DistrictCodeModel DistrictCodeNavigation { get; set; }
public TehsilCodeModel TehsilCodeNavigation { get; set; }
}
Below is the code I am trying to use.
if (User=="farmer")
{
var tbFarmerInfo = await
_farmerService.GetFarmerByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbFarmerInfo);
result.UserId = tbFarmerInfo.FarmerId;
result.UserName = tbFarmerInfo.FarmerName;
result.image = tbFarmerInfo.FarmerImage;
result.Role = "Farmer";
response.Data = result;
return response;
}
else if (User == "TSO")
{
string cellno = User.Claims.FirstOrDefault(c => c.Type ==
ClaimTypes.Name).Value.TrimStart('0');
var tbTsoInfo = await _tsoService.GetTSOByCellPhone(cellno);
var result = _Mapper.Map<UserProfileInfo>(tbTsoInfo);
result.UserId = tbTsoInfo.Tsoid;
result.UserName = tbTsoInfo.Tsoname;
result.image = tbTsoInfo.Tsoimage;
result.Role = "TSO";
response.Data = result;
return response;
}
The expected result should be that both models can be mapped in the viewModel.
Like, if I map the FarmerProfile it should be mapped and if I want to map TsoProfile it should be mapped too.
I'm not sure if this is possible or not, but I thought I would ask...
I have two database tables. One is a list of users pulled from Active Directory. The second table is a list of scheduled forwards. The relationship I would like to create would be...
public class AdObject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ObjectType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
public string PrimaryEmail { get; set; }
public string Alias { get; set; }
public string SamAccountName { get; set; }
public string PrimaryDisplay { get; set; }
public string CanonicalName { get; set; }
public string OU { get; set; }
public string CoreGroup { get; set; }
public string ForwardedTo { get; set; }
public bool? IsDisabled { get; set; }
public bool? IsForwarded { get; set; }
public bool? DeliverAndRedirect { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public DateTime? LastLogon { get; set; }
public DateTime? LastApiLogon { get; set; }
public DateTime? LastCheck { get; set; }
// This isn't required. But if possible I would like this to be
// a relationship to another AdObject whos "PrimaryEmail" matches
// the "ForwardedTo" column of this AdObject. There will not always
// be a match though, so not too important just wondering if its possible.
public AdObject ForwardedToObject { get; set; }
// This would be a list of forwards where the "ForwardFrom"
// column matches the "PrimaryEmail" of this AdObject.
public ICollection<Forward> ScheduledForwards { get; set; }
= new List<Forward>();
// FYI... Technically ID,SamAccountName,PrimaryEmail,DistinguishedName,
// and CanonicalName are all unique. They could all be keys.
}
public class Forward
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ForwardFrom { get; set; }
public string ForwardTo { get; set; }
public bool? DeliverAndRedirect { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? StopTime { get; set; }
public string Recurrence { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public string StartJobId { get; set; }
public string StopJobId { get; set; }
public string StartJobStatus { get; set; }
public string StopJobStatus { get; set; }
public DateTime? StartJobCompleted { get; set; }
public DateTime? StopJobCompleted { get; set; }
public DateTime? StartJobCreated { get; set; }
public DateTime? StopJobCreated { get; set; }
public string StartReason { get; set; }
public string StopReason { get; set; }
// This would be the AdObject whos "PrimaryEmail" matches the
// "ForwardTo" column.
public AdObject ForwardToObject { get; set; }
// This would be the AdObject whos "PrimaryEmail" matches the
// "ForwardFrom" column.
public AdObject ForwardFromObject { get; set; }
}
I think I got it figured out. I was having a hell of a time understanding the logic behind relationships. I had a few misconceptions that I ironed out and after going through every YouTube video, PluralSight Course and Udemy course I could find it finally started to click. I usually don't have this much trouble teaching myself these things, but the misconceptions I had were pointing me in the wrong direction. In the end I only had to specify the keys and two relationships (conventions did the rest).
public class AdObject
{
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ObjectType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
public string DistinguishedName { get; set; }
[Key, Column(Order = 1)]
public string PrimaryEmail { get; set; }
public string Alias { get; set; }
public string SamAccountName { get; set; }
public string PrimaryDisplay { get; set; }
public string CanonicalName { get; set; }
public string OU { get; set; }
public string CoreGroup { get; set; }
public bool? IsDisabled { get; set; }
public bool? IsForwarded { get; set; }
public bool? DeliverAndRedirect { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public DateTime? LastLogon { get; set; }
public DateTime? LastApiLogon { get; set; }
public DateTime? LastCheck { get; set; }
public AdObject ForwardedToObject { get; set; }
public ICollection<Forward> ForwardRecipientSchedule { get; set; }
= new List<Forward>();
public ICollection<Forward> ForwardSchedule { get; set; }
= new List<Forward>();
}
public class Forward
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public AdObject ForwardFromObject { get; set; }
public AdObject ForwardToObject { get; set; }
public bool? DeliverAndRedirect { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? StopTime { get; set; }
public string Recurrence { get; set; }
public bool? DisableForwardAtLogon { get; set; }
public DateTime? DisableAtLogonAfter { get; set; }
public string Notify { get; set; }
public string StartJobId { get; set; }
public string StopJobId { get; set; }
public string StartJobStatus { get; set; }
public string StopJobStatus { get; set; }
public DateTime? StartJobCompleted { get; set; }
public DateTime? StopJobCompleted { get; set; }
public DateTime? StartJobCreated { get; set; }
public DateTime? StopJobCreated { get; set; }
public string StartReason { get; set; }
public string StopReason { get; set; }
}
public class EntityContext : DbContext
{
public EntityContext() : base("name=EnityContext"){
}
public DbSet<AdObject> AdObjects { get; set; }
public DbSet<Forward> Forwards { get; set; }
//protected override void OnConfiguring(DbContext)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AdObject>()
.HasMany(f => f.ForwardSchedule)
.WithRequired(f => f.ForwardFromObject)
.WillCascadeOnDelete(false);
modelBuilder.Entity<AdObject>()
.HasMany(f => f.ForwardRecipientSchedule)
.WithRequired(f => f.ForwardToObject)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}
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();
}
}