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; }
}
Related
(Complete noob here, appologies if I'm unclear!) I have been using Riot Games' API to get information of a players stats on specific characters in a game. I used Json2CSharp in order to create the following data object.
public class Data
{
public Aatrox Aatrox { get; set; }
public Ahri Ahri { get; set; }
public Akali Akali { get; set; }
public Alistar Alistar { get; set; }
public Amumu Amumu { get; set; }
public Anivia Anivia { get; set; }
public Annie Annie { get; set; }
public Ashe Ashe { get; set; }
public AurelionSol AurelionSol { get; set; }
public Azir Azir { get; set; }
public Bard Bard { get; set; }
public Blitzcrank Blitzcrank { get; set; }
public Brand Brand { get; set; }
public Braum Braum { get; set; }
public Caitlyn Caitlyn { get; set; }
public Camille Camille { get; set; }
public Cassiopeia Cassiopeia { get; set; }
public Chogath Chogath { get; set; }
public Corki Corki { get; set; }
public Darius Darius { get; set; }
public Diana Diana { get; set; }
public Draven Draven { get; set; }
public DrMundo DrMundo { get; set; }
public Ekko Ekko { get; set; }
public Elise Elise { get; set; }
public Evelynn Evelynn { get; set; }
public Ezreal Ezreal { get; set; }
public FiddleSticks FiddleSticks { get; set; }
public Fiora Fiora { get; set; }
public Fizz Fizz { get; set; }
public Galio Galio { get; set; }
public Gangplank Gangplank { get; set; }
public Garen Garen { get; set; }
public Gnar Gnar { get; set; }
public Gragas Gragas { get; set; }
public Graves Graves { get; set; }
public Hecarim Hecarim { get; set; }
public Heimerdinger Heimerdinger { get; set; }
public Illaoi Illaoi { get; set; }
public Irelia Irelia { get; set; }
public Ivern Ivern { get; set; }
public Janna Janna { get; set; }
public JarvanIV JarvanIV { get; set; }
public Jax Jax { get; set; }
public Jayce Jayce { get; set; }
public Jhin Jhin { get; set; }
public Jinx Jinx { get; set; }
public Kalista Kalista { get; set; }
public Karma Karma { get; set; }
public Karthus Karthus { get; set; }
public Kassadin Kassadin { get; set; }
public Katarina Katarina { get; set; }
public Kayle Kayle { get; set; }
public Kennen Kennen { get; set; }
public Khazix Khazix { get; set; }
public Kindred Kindred { get; set; }
public Kled Kled { get; set; }
public KogMaw KogMaw { get; set; }
public Leblanc Leblanc { get; set; }
public LeeSin LeeSin { get; set; }
public Leona Leona { get; set; }
public Lissandra Lissandra { get; set; }
public Lucian Lucian { get; set; }
public Lulu Lulu { get; set; }
public Lux Lux { get; set; }
public Malphite Malphite { get; set; }
public Malzahar Malzahar { get; set; }
public Maokai Maokai { get; set; }
public MasterYi MasterYi { get; set; }
public MissFortune MissFortune { get; set; }
public MonkeyKing MonkeyKing { get; set; }
public Mordekaiser Mordekaiser { get; set; }
public Morgana Morgana { get; set; }
public Nami Nami { get; set; }
public Nasus Nasus { get; set; }
public Nautilus Nautilus { get; set; }
public Nidalee Nidalee { get; set; }
public Nocturne Nocturne { get; set; }
public Nunu Nunu { get; set; }
public Olaf Olaf { get; set; }
public Orianna Orianna { get; set; }
public Pantheon Pantheon { get; set; }
public Poppy Poppy { get; set; }
public Quinn Quinn { get; set; }
public Rammus Rammus { get; set; }
public RekSai RekSai { get; set; }
public Renekton Renekton { get; set; }
public Rengar Rengar { get; set; }
public Riven Riven { get; set; }
public Rumble Rumble { get; set; }
public Ryze Ryze { get; set; }
public Sejuani Sejuani { get; set; }
public Shaco Shaco { get; set; }
public Shen Shen { get; set; }
public Shyvana Shyvana { get; set; }
public Singed Singed { get; set; }
public Sion Sion { get; set; }
public Sivir Sivir { get; set; }
public Skarner Skarner { get; set; }
public Sona Sona { get; set; }
public Soraka Soraka { get; set; }
public Swain Swain { get; set; }
public Syndra Syndra { get; set; }
public TahmKench TahmKench { get; set; }
public Taliyah Taliyah { get; set; }
public Talon Talon { get; set; }
public Taric Taric { get; set; }
public Teemo Teemo { get; set; }
public Thresh Thresh { get; set; }
public Tristana Tristana { get; set; }
public Trundle Trundle { get; set; }
public Tryndamere Tryndamere { get; set; }
public TwistedFate TwistedFate { get; set; }
public Twitch Twitch { get; set; }
public Udyr Udyr { get; set; }
public Urgot Urgot { get; set; }
public Varus Varus { get; set; }
public Vayne Vayne { get; set; }
public Veigar Veigar { get; set; }
public Velkoz Velkoz { get; set; }
public Vi Vi { get; set; }
public Viktor Viktor { get; set; }
public Vladimir Vladimir { get; set; }
public Volibear Volibear { get; set; }
public Warwick Warwick { get; set; }
public Xerath Xerath { get; set; }
public XinZhao XinZhao { get; set; }
public Yasuo Yasuo { get; set; }
public Yorick Yorick { get; set; }
public Zac Zac { get; set; }
public Zed Zed { get; set; }
public Ziggs Ziggs { get; set; }
public Zilean Zilean { get; set; }
public Zyra Zyra { get; set; }
}
each champion's respective object looking like the below:
public class Ziggs
{
public string version { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
public string blurb { get; set; }
public Info132 info { get; set; }
public Image132 image { get; set; }
public List<string> tags { get; set; }
public string partype { get; set; }
public Stats132 stats { get; set; }
}
What I'm trying to do is get at the ID for each champion, and have been trying with the for loop below:
foreach (var champion in ChampionData.data.GetType().GetProperties())
{
Console.WriteLine(champion.id);
}
This however does not seem to allow me to access the ID, nor any of the other properties of the objects. I have been able to access the values calling them indervisually, however cannot figure out how I can iterate through the object.
Any advise would be really appreciated!
Edit: Here is where I'm getting the Json from: http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json
As described in the comments you need to define a single class that represents all of the Champions. In the example below I have simply renamed the Ziggs class in your question to Champion:
public class Champion
{
public string version { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public string title { get; set; }
public string blurb { get; set; }
public Info132 info { get; set; }
public Image132 image { get; set; }
public List<string> tags { get; set; }
public string partype { get; set; }
public Stats132 stats { get; set; }
}
Now you need to change your ChampionData class to use a dictionary to store these objects:
public class ChampionData
{
public string Type { get; set; }
public string Format { get; set; }
public string Version { get; set; }
public Dictionary<string, Champion> Data { get; set; }
}
We have used a Dictionary<string, Champion> to represent the data elements in the JSON. Note the name needs to be Data to match the name in the JSON.
The parser will automatically parse the JSON into the dictionary, using the strings as the dictionary key:
"data": {
"Aatrox": { "..." },
"Ahri": { "..." },
"Akali": { "..." },
So, "Aatrox", "Ahri", "Akali" will be the string part of the dictionary (i.e. the Key) and the Champion part of the dictionary (i.e. the Value) will contain all the data that is under each champion in the JSON.
You can now easily access any property of each Champion easily. So your foreach loop can be:
foreach (var c in data.Data)
{
Console.WriteLine(c.Value.id);
}
NOTE: We need to use the Value property to access each Champion object that is linked to the Key part of the Dictionary
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);
}
}
Introducing FOREIGN KEY constraint 'FK_dbo.Queries_dbo.Users_UserID' on table 'Queries' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
public partial class User
{
public User()
{
this.Alerts = new HashSet<Alert>();
this.DeviceTokens = new HashSet<DeviceToken>();
this.MobileNotifications = new HashSet<MobileNotification>();
this.Queries = new HashSet<Query>();
this.SendQueries = new HashSet<SendQuery>();
}
public int ID { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SSOID { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public int LatestUpdatedRecord { get; set; }
public virtual ICollection<Alert> Alerts { get; set; }
public virtual ICollection<DeviceToken> DeviceTokens { get; set; }
public virtual ICollection<MobileNotification> MobileNotifications { get; set; }
public virtual ICollection<Query> Queries { get; set; }
public virtual ICollection<SendQuery> SendQueries { get; set; }
}
public partial class Query
{
public Query()
{
this.AlertEmails = new HashSet<AlertEmail>();
this.Alerts = new HashSet<Alert>();
this.QueryFacets = new HashSet<QueryFacet>();
}
public int ID { get; set; }
public int UserID { get; set; }
public string EntityType { get; set; }
public string Name { get; set; }
public string SearchTerm { get; set; }
public string OrderBy { get; set; }
public string QueryType { get; set; }
public string ReceiveUpdateTime { get; set; }
public Nullable<System.DateTime> NextSendTime { get; set; }
public bool IsActive { get; set; }
public string Token { get; set; }
public string AlertName { get; set; }
public bool Enabled { get; set; }
public bool GetNotifications { get; set; }
public string TimeFilterType { get; set; }
public string TimeFilterValue { get; set; }
public string RectangleFilter { get; set; }
public virtual ICollection<AlertEmail> AlertEmails { get; set; }
public virtual ICollection<Alert> Alerts { get; set; }
public virtual ICollection<QueryFacet> QueryFacets { get; set; }
public virtual User User { get; set; }
}
public partial class SearchAndAlertDbContext : DbContext
{
public virtual DbSet<AlertEmail> AlertEmails { get; set; }
public virtual DbSet<AlertingTime> AlertingTimes { get; set; }
public virtual DbSet<Alert> Alerts { get; set; }
public virtual DbSet<DeviceToken> DeviceTokens { get; set; }
public virtual DbSet<IgnoredSlide> IgnoredSlides { get; set; }
public virtual DbSet<Log> Logs { get; set; }
public virtual DbSet<MobileNotification> MobileNotifications { get; set; }
public virtual DbSet<Query> Queries { get; set; }
public virtual DbSet<QueryFacet> QueryFacets { get; set; }
public virtual DbSet<SendQuery> SendQueries { get; set; }
public virtual DbSet<StoredQuery> StoredQueries { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<BlockedUserForActivity> BlockedUserForActivities { get; set; }
public virtual DbSet<UserActivity> UserActivities { get; set; }
public virtual DbSet<UserActivityIgnoreList> UserActivityIgnoreLists { get; set; }
public virtual DbSet<UserActivityMonitor> UserActivityMonitors { get; set; }
public virtual DbSet<UserActivitySpecificSetting> UserActivitySpecificSettings { get; set; }
public virtual DbSet<WarnedUserForActivity> WarnedUserForActivities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().
HasMany(p => p.Queries).
WithRequired(a => a.User).
HasForeignKey(a => a.UserID).WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
}
Tell EF not to cascade the query delete.
modelBuilder.Entity<Query>()
.HasRequired(q => q.User)
.WithMany(s => s.Queries)
.HasForeignKey(s => s.UserId)
.WillCascadeOnDelete(false);
Or turn off the convention:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
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; }
again i am stucked with un-clrear error raised by EF. I have the following model class:-
public partial class TMSServer
{
public TMSServer()
{
this.TMSServers1 = new HashSet<TMSServer>();
this.TMSVirtualMachines = new HashSet<TMSVirtualMachine>();
}
public int TMSServerID { get; set; }
public Nullable<int> ServerModelID { get; set; }
public int DataCenterID { get; set; }
public string ILOIP { get; set; }
public int RackID { get; set; }
public Nullable<int> StatusID { get; set; }
public Nullable<int> BackUpStatusID { get; set; }
public int RoleID { get; set; }
public Nullable<int> OperatingSystemID { get; set; }
public Nullable<int> VirtualCenterID { get; set; }
public string Comment { get; set; }
public byte[] timestamp { get; set; }
public long IT360SiteID { get; set; }
public virtual DataCenter DataCenter { get; set; }
public virtual OperatingSystem OperatingSystem { get; set; }
public virtual ServerModel ServerModel { get; set; }
public virtual Technology Technology { get; set; }
public virtual TechnologyBackUpStatu TechnologyBackUpStatu { get; set; }
public virtual TechnologyRole TechnologyRole { get; set; }
public virtual TechnologyStatu TechnologyStatu { get; set; }
public virtual TMSRack TMSRack { get; set; }
public virtual ICollection<TMSServer> TMSServers1 { get; set; }
public virtual TMSServer TMSServer1 { get; set; }
public virtual ICollection<TMSVirtualMachine> TMSVirtualMachines { get; set; }
}
}
and the following post create action method:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ServerJoin sj, FormCollection formValues)
{
string controllername = RouteData.Values["controller"].ToString();
if (ModelState.IsValid)
{
//code goes here
repository.InsertOrUpdateServer(sj.Server, User.Identity.Name, assetid);
repository.Save()
and the following Repository method:-
public void InsertOrUpdateServer(TMSServer server, string username,long assetid)
{
var resource = GetResourceDetials(assetid);
if (server.TMSServerID == default(int))
{
// New entity
int technologyypeID = GetTechnologyTypeID("Server");
Technology technology = new Technology
{
IsDeleted = true,
TypeID = technologyypeID,
Tag = "S" + GetTagMaximumeNumber(technologyypeID).ToString(),
StartDate = DateTime.Now,
IT360ID = assetid
};
InsertOrUpdateTechnology(technology);
Save();
var auditinfo = IntiateTechnologyAudit(tms.AuditActions.SingleOrDefault(a => a.Name.ToUpper() == "ADD").ID,
tms.TechnologyTypes.SingleOrDefault(a => a.Name.ToUpper() == "Server").AssetTypeID,
username, technology.TechnologyID);
server.TMSServerID= technology.TechnologyID;
server.IT360SiteID = resource.SITEID.Value;
tms.TMSServers.Add(server);
technology.IsDeleted = false;
InsertOrUpdateTechnology(technology);
InsertOrUpdateTechnologyAudit(auditinfo);
}
}
;
But when i try to call the Post Create action method i will get the following exception:-
System.InvalidOperationException was unhandled by user code
HResult=-2146233079 Message=Multiplicity constraint violated. The
role 'TMSServers' of the relationship 'TMSModel.FK_Servers_Technology'
has multiplicity 1 or 0..1. Source=System.Data.Entity StackTrace:
The Technology model class which is envlved in the exception looks as follow:-
public partial class Technology
{
public Technology()
{
this.TMSSwitchPorts = new HashSet<TMSSwitchPort>();
this.TechnologyAudits = new HashSet<TechnologyAudit>();
this.TechnologyIPs = new HashSet<TechnologyIP>();
}
public int TechnologyID { get; set; }
public string Tag { get; set; }
public bool IsDeleted { get; set; }
public byte[] timestamp { get; set; }
public Nullable<int> TypeID { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<long> IT360ID { get; set; }
public virtual TMSFirewall TMSFirewall { get; set; }
public virtual TMSRack TMSRack { get; set; }
public virtual TMsRouter TMsRouter { get; set; }
public virtual TMSServer TMSServer { get; set; }
public virtual TMSStorageDevice TMSStorageDevice { get; set; }
public virtual TMSSwitch TMSSwitch { get; set; }
public virtual ICollection<TMSSwitchPort> TMSSwitchPorts { get; set; }
public virtual TechnologyType TechnologyType { get; set; }
public virtual ICollection<TechnologyAudit> TechnologyAudits { get; set; }
public virtual ICollection<TechnologyIP> TechnologyIPs { get; set; }
public virtual TMSVirtualMachine TMSVirtualMachine { get; set; }
}