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>();
Related
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; }
}
I'm having some issues with EF.
Migrations go fine, but when I try to run update-database I get the error :
Unable to determine the principal end of the 'LeagueInsight.Models.Image_Passive' relationship. Multiple added entities may have the same primary key.
Here are my models and config:
Passive.cs
public class Passive
{
public long Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public string SanitizedDescription { get; set; }
// Navigation
public virtual Image Image { get; set; }
public virtual Champion Champion { get; set; }
}
Image.cs
public class Image
{
public long Id { get; set; }
public string Full { get; set; }
public string Group { get; set; }
public int H { get; set; }
public string Sprite { get; set; }
public int W { get; set; }
public int X { get; set; }
public int Y { get; set; }
// Navigation
public virtual Champion Champion { get; set; }
public virtual ChampionSpell ChampionSpell { get; set; }
public virtual Passive Passive { get; set; }
}
DBContext Configuration Partial:
modelBuilder.Entity<Passive>()
.HasRequired(p => p.Champion)
.WithRequiredPrincipal(c => c.Passive);
modelBuilder.Entity<Info>()
.HasRequired(i => i.Champion)
.WithRequiredPrincipal(c => c.Info);
modelBuilder.Entity<Image>()
.HasOptional(i => i.Champion)
.WithRequired(c => c.Image);
modelBuilder.Entity<Image>()
.HasOptional(i => i.Passive)
.WithRequired(p => p.Image);
base.OnModelCreating(modelBuilder);
It is just supposed to be a 1-1 relationship between the two, an I can't figure out why there would be multiple entities with the same Id here.
Edit: I was asked for the champion class:
public class Champion
{
public int Id { get; set; }
public string Blurb { get; set; }
public string Key { get; set; }
public string Lore { get; set; }
public string Name { get; set; }
public string Partype { get; set; }
public string Title { get; set; }
// Navigation
[InverseProperty("Ally")]
public virtual ICollection<Tip> Allytips { get; set; }
[InverseProperty("Enemy")]
public virtual ICollection<Tip> Enemytips { get; set; }
public virtual Image Image { get; set; }
public virtual Info Info { get; set; }
public virtual Passive Passive { get; set; }
public virtual ICollection<Recommended> Recommended { get; set; }
public virtual ICollection<Skin> Skins { get; set; }
public virtual Stats Stats { get; set; }
public virtual ICollection<ChampionSpell> Spells { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
Here is my codes;
public List<SbtKlasorViewModel> GetFoldersWithIndexedDocuments()
{
//TODO - I can't find right query. We need folders with documents but only documents which be Indexed
using (ISession session = DatabaseProvider.SessionFactory.OpenSession())
{
List<DokumanlarModel> dokumanList = session.QueryOver<DokumanlarModel>()
.Where(x => x.IndexlenmeTarihi != null)
.List().ToList();
var list = dokumanList.GroupBy(x => x.Klasor.Aciklama);
List<SbtKlasorModel> folders = list as List<SbtKlasorModel>;
////Transforming SbtKlasorModel to SbtKlasorViewModel for respose
List<SbtKlasorViewModel> transformedFolders = folders
.Select(x => ModelTransformer.TransformModel(x)).ToList();
return transformedFolders;
}
}
DokumanlarModel.cs:
public class DokumanlarModel : SModuleClass
{
public virtual int DokumanId { get; set; }
public virtual string DokumanAdi { get; set; }
public virtual int DosyaBoyutu { get; set; }
public virtual int Durum { get; set; }
public virtual string EskiPath { get; set; }
public virtual string IndexTahsisKullanici { get; set; }
public virtual DateTime? IndexlenmeTarihi { get; set; }
public virtual string IndexleyenKullanici { get; set; }
public virtual string KaliteKontrolKullanici { get; set; }
public virtual DateTime? KaliteKontrolTarihi { get; set; }
public virtual SbtKlasorModel Klasor { get; set; }
public virtual int KlasordekiSira { get; set; }
public virtual DokNitelikTipModel NitelikTipId { get; set; }
public virtual int OcrDurum { get; set; }
public virtual string Path { get; set; }
public virtual int SayfaSayisi { get; set; }
public virtual DateTime? TaranmaTarihi { get; set; }
public virtual string TarayanKullanici { get; set; }
public virtual int Versiyon { get; set; }
public virtual string OrjinalPath { get; set; }
public virtual IList<LogDokumanModel> LogDokumanList { get; set; }
public virtual IList<DokumanlarOcrModel> DokumanlarOcrList { get; set; }
public virtual IList<DokVersiyonModel> DokVersiyonList { get; set; }
public virtual IList<DokMetaDataArsivModel> DokMetaDataArsivList { get; set; }
public DokumanlarModel()
{
LogDokumanList = new List<LogDokumanModel>();
DokumanlarOcrList = new List<DokumanlarOcrModel>();
DokVersiyonList = new List<DokVersiyonModel>();
DokMetaDataArsivList = new List<DokMetaDataArsivModel>();
}
}
SbtKlasorModel.cs:
public class SbtKlasorModel : SModuleClass
{
public virtual int KlasorId { get; set; }
public virtual string Aciklama { get; set; }
public virtual string Ada { get; set; }
public virtual string KisiAdSoyad { get; set; }
public virtual string Mahalle { get; set; }
public virtual string Parsel { get; set; }
public virtual string SerhAciklama { get; set; }
public virtual DateTime SerhBaslangicTarihi { get; set; }
public virtual DateTime SerhBitisTarihi { get; set; }
public virtual SbtKullaniciModel SerhKullanici { get; set; }
public virtual string Pafta { get; set; }
public virtual string KlasorNo { get; set; }
public virtual string SiraNo { get; set; }
public virtual string AciklamaYeni { get; set; }
public virtual IList<IlskGrupKlasorModel> IlskGrupKlasorList { get; set; }
public virtual IList<DokumanlarModel> DokumanlarList { get; set; }
public virtual IList<DokTaleplerModel> DokTaleplerList { get; set; }
public SbtKlasorModel()
{
IlskGrupKlasorList = new List<IlskGrupKlasorModel>();
DokumanlarList = new List<DokumanlarModel>();
DokTaleplerList = new List<DokTaleplerModel>();
}
}
I got data like List from database. And grouped by "DokumanlarModel.Klasor.Aciklama". But I need List list. I tried like above. It returns null. What should i do for this type change?
public List<SbtKlasorViewModel> GetFoldersWithIndexedDocuments()
{
using (var session = DatabaseProvider.SessionFactory.OpenSession())
{
var foldersContainingIndexedDocs = session.QueryOver<SbtKlasorModel>()
.JoinQueryOver<DokumanlarModel>(x => x.DokumanlarList)
.Where(doc => doc.IndexlenmeTarihi != null)
.List();
//Transforming SbtKlasorModel to SbtKlasorViewModel for respose
return folders.Select(ModelTransformer.TransformModel).ToList();
}
}
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; }
}
I'm trying to write a many-to-many relationship in the override of the onModelCreating method of my context in ASP.NET MVC4. I think I have my classes wrong because I'm getting errors in Intellisense that I don't understand. Here is my override:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Software>().
HasMany(i => i.LocationId).
WithMany(c => c.SoftwareId).
Map(mc =>
{
mc.MapLeftKey("SoftwareId");
mc.MapRightKey("LocationId");
mc.ToTable("SoftwareLocations");
});
}
Here is my Software class:
public class Software
{
public int Id { get; set; }
public virtual List<SoftwareType> SoftwareTypes { get; set; }
public virtual List<Location> Locations { get; set; }
public virtual List<SoftwarePublisher> Publishers { get; set; }
[Required]
[StringLength(128)]
public string Title { get; set; }
[Required]
[StringLength(10)]
public string Version { get; set; }
[Required]
[StringLength(128)]
public string SerialNumber { get; set; }
[Required]
[StringLength(3)]
public string Platform { get; set; }
[StringLength(1000)]
public string Notes { get; set; }
[Required]
[StringLength(15)]
public string PurchaseDate { get; set; }
public bool Suite { get; set; }
public string SubscriptionEndDate { get; set; }
//[Required]
//[StringLength(3)]
public int SeatCount { get; set; }
public virtual Location LocationId { get; set; }
}
Here is my Location class:
public class Location
{
public int Id { get; set; }
[Required]
[StringLength(20)]
public string LocationName { get; set; }
public virtual Software SoftwareId { get; set; }
}
How do I write my Fluent override so I can map them correctly?
Many-to-Many means that in both entities is Collections. So you should set HasMany(software=>software.Locations) and set WithMany(location=>location.Softwares) as in example:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Software>().
HasMany(i => i.Locations).
WithMany(c => c.Softwares).
Map(mc =>
{
mc.MapLeftKey("SoftwareId");
mc.MapRightKey("LocationId");
mc.ToTable("SoftwareLocations");
});
}
Here is my Software class:
public class Software
{
public int Id { get; set; }
public virtual List<SoftwareType> SoftwareTypes { get; set; }
public virtual ICollection <Location> Locations { get; set; }
public virtual List<SoftwarePublisher> Publishers { get; set; }
[Required]
[StringLength(128)]
public string Title { get; set; }
[Required]
[StringLength(10)]
public string Version { get; set; }
[Required]
[StringLength(128)]
public string SerialNumber { get; set; }
[Required]
[StringLength(3)]
public string Platform { get; set; }
[StringLength(1000)]
public string Notes { get; set; }
[Required]
[StringLength(15)]
public string PurchaseDate { get; set; }
public bool Suite { get; set; }
public string SubscriptionEndDate { get; set; }
//[Required]
//[StringLength(3)]
public int SeatCount { get; set; }
}
Here is my Location class:
public class Location
{
public int Id { get; set; }
[Required]
[StringLength(20)]
public string LocationName { get; set; }
public virtual ICollection<Software> Softwares { get; set; }
}