How to use Fluent API to map foreign key - c#

I am trying to use modelBuilder to map a foreign Key in my database. I need to post the Id into JobTESPM_EmployeeId instead of JOBTESPMId. I have been using this a guide but I can't see where the examples are the same as my setup. http://msdn.microsoft.com/en-in/data/jj591620.aspx#IndependentAssociation
public class Job
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public Int64? JobId { get; set; }
public int? JobNumber { get; set; }
public string JobName { get; set; }
public int? JobTypeId { get; set; }
public int? CustomerEmployeePMId { get; set; }
public virtual CustomerEmployee CustomerEmployeePM { get; set; }
public int? CustomerEmployeeAdminId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAdmin { get; set; }
public int? CustomerEmployeeAccountantId { get; set; }
public virtual CustomerEmployee CustomerEmployeeAccountant { get; set; }
public int? CustomerEmployeeSuperintendentId { get; set; }
public virtual CustomerEmployee CustomerEmployeeSuperintendent { get; set; }
public int? JobTESPMId { get; set; }
public virtual Employee JobTESPM { get; set; }
public int? JobTESSuperintendentId { get; set; }
public virtual Employee JobTESSuperintendent { get; set; }
}
public class Employee
{
public int EmployeeId { get; set; }
public string AccountName { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeLastName { get; set; }
public string EmployeeTitle { get; set; }
public Int64? EmployeeCellPhone { get; set; }
public Int64? EmployeeOfficePhone { get; set; }
public string EmployeeEmail { get; set; }
public int? CompanyEmployeeId { get; set; }
public bool? EmployeeHidden { get; set; }
public bool? EmployeeIsSuper { get; set; }
public bool? EmployeeIsPM { get; set; }
public string EmployeeAltEmail { get; set; }
}

What about adding a couple attributes...
[Column("JobTESPM_EmployeeID")]
public int? JobTESPMId { get; set; }
[ForeignKey("JobTESPMId")]
public virtual Employee JobTESPM { get; set; }

Related

Edit with viewmodel in entity frameworkcore

Hello I have a problem is that I cannot edit my model using a viewmodel and I tried to integrate the automapping but it did not work because in my viewmodel I have models at the Palce of properties I would like to know is if there is another simpler solution to make it work
error : System.InvalidOperationException : 'The instance of entity type 'SeDevisTest' cannot be tracked because another instance with the same key value for {'DevisId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
thank you
this is my Controller
public ActionResult edit(ViewModelEtudes viewModelEtudes)
{
ViewModelEtudes Etudes = new ViewModelEtudes();
serviceEtudesEnCours.remplirDrowdownliste(demId);
var resultDevis= _context.SeDevisTest.FirstOrDefault(item => item.DevisFkDemNum == demId);
if (resultDevis != null)
{
_context.Entry(viewModelEtudes.SeDevisTest).State = EntityState.Modified;
_context.SaveChanges();
}
return View(Etudes);
}
this is my view model it contains the entity that I will change se_devis
public class ViewModelEtudes
{
public SeDevisTest SeDevisTest { get; set; }
public SeDemande seDemandes { get; set; }
public SeInformationRecrutement InformationRecrutement { get; set; }
public SeControleProduit controleProduit { get; set; }
public SeQuestionnaire questionnaire { get; set; }
public SePersonnelSyres SePersonnelSyres { get; set; }
public SeTypeProduit SeTypeProduit { get; set; }
public List<SeCritereTest> SeCritereTest { get; set; }
public SePartenir sePartenirs { get; set; }
public SeTraitementDemande seTraitementDemandes { get; set; }
public SeInformationClient SeInformationClient { get; set; }
public SeClient SeInclient { get; set; }
public SeAssistantClient assitantclient { get; set; }
public SeReceptionProduit receptionProduit { get; set; }
public SePrestation prestation { get; set; }
public SeRapport seRapport { get; set; }
public SeResultat seResultat { get; set; }
public SeDemandeTypeProduit demandeTypeProduit { get; set; }
}
this is my Entity SE_DEVIS_TEST
public SeDevisTest()
{
Correspondance = new HashSet<Correspondance>();
SeCorrecponsance = new HashSet<SeCorrecponsance>();
SeFacture = new HashSet<SeFacture>();
SePlainte = new HashSet<SePlainte>();
SeQuestionnaire = new HashSet<SeQuestionnaire>();
SeRapport = new HashSet<SeRapport>();
}
public int DevisId { get; set; }
public DateTime? DevisDateCreation { get; set; }
public DateTime? DevisDateEnvoi { get; set; }
public bool? DevisAnnulation { get; set; }
public DateTime? DevisDateAnnulation { get; set; }
public int? DevisMotifAnnulationDesc { get; set; }
public bool? DevisConserverFacturation { get; set; }
public bool? DevisSigneReçu { get; set; }
public DateTime? DevisDateReception { get; set; }
public bool? DevisAttestationReçu { get; set; }
public DateTime? DevisDateReceptionAttestation { get; set; }
public string DevisConditionParticuliere { get; set; }
public int? DevisFkDemNum { get; set; }
public int? DevisFkSatisfaClientId { get; set; }
public int? DevisDiffcultéEstimé { get; set; }
public string DevisSy { get; set; }
public int? DevisNbRapport { get; set; }
public virtual SeQualiDifficulte DevisDiffcultéEstiméNavigation { get; set; }
public virtual SeTraitementDemande DevisFkDemNumNavigation { get; set; }
public virtual SeSatisfactionClient DevisFkSatisfaClient { get; set; }
public virtual SeColisage SeColisage { get; set; }
public virtual SeGestionBase SeGestionBase { get; set; }
public virtual SeInformationRecrutement SeInformationRecrutement { get; set; }
public virtual SeLettre SeLettre { get; set; }
public virtual SeOrganistationRecrutement SeOrganistationRecrutement { get; set; }
public virtual ICollection<Correspondance> Correspondance { get; set; }
public virtual ICollection<SeCorrecponsance> SeCorrecponsance { get; set; }
public virtual ICollection<SeFacture> SeFacture { get; set; }
public virtual ICollection<SePlainte> SePlainte { get; set; }
public virtual ICollection<SeQuestionnaire> SeQuestionnaire { get; set; }
public virtual ICollection<SeRapport> SeRapport { get; set; }
}

AutoMapperMappingException: Missing type map configuration or unsupported mapping

I'm attempting to use AutoMapper for the first time. The GSMSite maps fine, but I get an error when trying to map the GSMUnit:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Do I need to specify a relationship between GSMSite and GSMUnits?
Domain class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Telephone { get; set; }
public bool PasswordReset { get; set; } = false;
public virtual ICollection<GSMSite> GSMSites { get; set; }
}
public class GSMSite
{
public int Id { get; set; }
public string SiteName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Town { get; set; }
public string Postcode { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<GSMUnit> GSMUnits { get; set; }
}
public class GSMUnit
{
public int Id { get; set; }
public string Model { get; set; }
public string Firmware { get; set; }
public string TelephoneNum { get; set; }
public int GSMSiteId { get; set; }
public virtual GSMSite GSMSite { get; set; }
}
Contract class:
public class GSMResponse
{
public int Id { get; set; }
public string Model { get; set; }
public string Firmware { get; set; }
public string TelephoneNum { get; set; }
}
public class SiteResponse
{
public int Id { get; set; }
public string SiteName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Town { get; set; }
public string Postcode { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
}
Mapping:
public DomainToResponseProfile()
{
CreateMap<GSMSite, SiteResponse>();
CreateMap<GSMUnit, GSMResponse>();
}

Map multiple different models into single View Model - AutoMapper

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.

C# Entity Framework - Multiple relationships

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

Why is a new object not saved when adding it to a list of an existing object in EF4?

I retrieve an existing customer from the database by it's id. This customer has a list of certificates. So I have: customer.CertificatesAsInvestor.
When I create a new certificate (var cert = new Certificate()) and add this object to the list customer.CertificatesAsInvestor.Add(cert) and then call SaveChanges(), the new certificate is not stored in the Database.
Why is this and what do I have to do to get this to work?
Customer class:
public partial class Customer
{
public Customer()
{
this.Deceased = false;
this.CertificatesAsInvestor = new HashSet<Certificate>();
this.CertificatesAsBeneficiary = new HashSet<Certificate>();
this.BankAccounts = new HashSet<BankAccount>();
this.Notes = new HashSet<Note>();
this.Documents = new HashSet<Document>();
this.Name = new PersonName();
}
public int Id { get; set; }
public string Code { get; set; }
public string CompanyName { get; set; }
public string EmailAddress { get; set; }
public System.DateTime BirthDate { get; set; }
public string BSNNo { get; set; }
public string IdCardNo { get; set; }
public bool Deceased { get; set; }
public Kompas.Bas.Gender Gender { get; set; }
public Kompas.Bas.Title Title { get; set; }
public string DayPhone { get; set; }
public string OtherPhone { get; set; }
public Kompas.Bas.CustomerStatus Status { get; set; }
public PersonName Name { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Certificate> CertificatesAsInvestor { get; set; }
public virtual ICollection<Certificate> CertificatesAsBeneficiary { get; set; }
public virtual Address PostalAddress { get; set; }
public virtual ICollection<BankAccount> BankAccounts { get; set; }
public virtual ICollection<Note> Notes { get; set; }
public virtual ICollection<Document> Documents { get; set; }
}
Certificate:
public partial class Certificate
{
public Certificate()
{
this.Transactions = new HashSet<Transaction>();
this.Notes = new HashSet<Note>();
this.Clicks = new HashSet<Click>();
this.ParticipationCalculations = new HashSet<ParticipationCalculation>();
}
public int Id { get; set; }
public int CertificateNo { get; set; }
public decimal NominalFee { get; set; }
public bool IsSigned { get; set; }
public System.DateTime DateIn { get; set; }
public Nullable<System.DateTime> ReturnDate { get; set; }
public Nullable<System.DateTime> OrderDate { get; set; }
public Nullable<System.DateTime> DateStop { get; set; }
public Kompas.Bas.Paymethod Paymethod { get; set; }
public Kompas.Bas.CertificateStatus Status { get; set; }
public Nullable<int> DexContractNumber { get; set; }
public Nullable<int> CollectionId { get; set; }
public Nullable<System.DateTime> FinalDateMin { get; set; }
public Nullable<System.DateTime> FinalDateMax { get; set; }
public bool Gift { get; set; }
public decimal PurchaseRate { get; set; }
public decimal PurchaseRateDiscount { get; set; }
public Nullable<System.DateTime> PayStopDate { get; set; }
public decimal GuaranteeValue { get; set; }
public int PaidTermCount { get; set; }
public decimal DepositNominal { get; set; }
public string SecondName { get; set; }
public Nullable<System.DateTime> SecondBirthDate { get; set; }
public virtual Customer InvestingCustomer { get; set; }
public virtual Customer BeneficiaryCustomer { get; set; }
public virtual InvestorRole InvestorRole { get; set; }
public virtual Product Product { get; set; }
public virtual BankAccount CollectionBankAccount { get; set; }
public virtual BankAccount PaymentBankAccount { get; set; }
public virtual Origin Origin { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Note> Notes { get; set; }
public virtual ICollection<Click> Clicks { get; set; }
public virtual ICollection<ParticipationCalculation> ParticipationCalculations { get; set; }
}

Categories