Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 数据库优先&;错误:无法确定从属操作的有效顺序_Asp.net Mvc_Entity Framework - Fatal编程技术网

Asp.net mvc 数据库优先&;错误:无法确定从属操作的有效顺序

Asp.net mvc 数据库优先&;错误:无法确定从属操作的有效顺序,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,我对我正在做的项目有问题。在POST:Edit上,它保存我的更改。在POST:Create上,我收到以下错误:“无法确定依赖操作的有效顺序。依赖可能由于外键约束、模型要求或存储生成的值而存在。” 所以我做了我的老师在大学里教我们的:我只是在谷歌上搜索。然而,答案是建议更改ModelBuilder fluent API。我不认为这是不合适的,因为我使用数据库优先的方法(它说它只适用于代码优先)并且我的保存在编辑中起作用。因为我想使用ViewModels,所以我遵循了以下步骤。我甚至找到并发布了一个

我对我正在做的项目有问题。在POST:Edit上,它保存我的更改。在POST:Create上,我收到以下错误:“无法确定依赖操作的有效顺序。依赖可能由于外键约束、模型要求或存储生成的值而存在。”

所以我做了我的老师在大学里教我们的:我只是在谷歌上搜索。然而,答案是建议更改ModelBuilder fluent API。我不认为这是不合适的,因为我使用数据库优先的方法(它说它只适用于代码优先)并且我的保存在编辑中起作用。因为我想使用ViewModels,所以我遵循了以下步骤。我甚至找到并发布了一个关于Create方法的教程解决方案来帮助我解决问题。请帮帮我。我正要把电脑扔出窗外。这有点复杂,因为它们是由钢化玻璃制成的

下面是我的模型的元数据(为了可读性,使用了最小的数据注释):

public partial class Employe
{
    sealed class Metadata
    {
        [Key]
        public int IdEmploye { get; set; }


        public string NomEmploye { get; set; }


        public string PrenomEmploye { get; set; }


        [ForeignKey("TitreEmploye_IdTitre")]            
        public int IdTitre { get; set; }


        [ForeignKey("Departement_IdDepartement")]            
        public int IdDepartement { get; set; }


        [ForeignKey("Employe_IdSuperviseur")]            
        public int IdSuperviseur { get; set; }


        public System.DateTime DateEmbauche { get; set; }


        public Nullable<System.DateTime> DateDepart { get; set; }


        public string StatutEmploye { get; set; }


        [ForeignKey("Employeur_IdEmployeur")]            
        public int IdEmployeur { get; set; }


        [ForeignKey("Localisation_IdLocalisation")]            
        public int IdLocalisation { get; set; }


        public string Langue { get; set; }


        public Nullable<bool> CarteAcces { get; set; }


        [ForeignKey("TelephoneBureau_IdTelephoneBureau")]            
        public Nullable<int> IdTelephoneBureau { get; set; }


        public Nullable<bool> CarteAffaire { get; set; }


        public string AdresseCourriel { get; set; }


        public bool CodeAlarme { get; set; }


        public System.DateTime DateNaissance { get; set; }


        public Nullable<bool> IsSuperviseur { get; set; }


        public Nullable<bool> IsActif { get; set; }
    }
}

现在怎么办?

我找到了!这是我的解决方案,以防其他人也遇到同样的问题

出于某种奇怪的原因,Visual Studio在一些多对多表名称的末尾添加了一个“1”。实体框架不喜欢它(我也不喜欢),因此我在模型中重命名了它们:

例如:

public Employe()
{
    this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
    this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
    this.CleBatiment1 = new HashSet<CleBatiment>();
    this.EquipementInfo = new HashSet<EquipementInfo>();
    this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
    this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
    this.Employe1 = new HashSet<Employe>();
}
public Employe()
{
this.accesapplicationf1=新的HashSet();
this.telephoneCellAirE1=新哈希集();
this.CleBatiment1=新的HashSet();
this.equipmentInfo=new HashSet();
this.GroupeSecurite1=新的HashSet();
this.vehicleCompagnie1=新哈希集();
this.Employe1=新的HashSet();
}
成为:

this.AccesApplicatif = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire = new HashSet<TelephoneCellulaire>();
this.CleBatiment = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
this.AccesApplicatif=new HashSet();
this.TelephoneCellulaire=新HashSet();
this.CleBatiment=new HashSet();
this.equipmentInfo=new HashSet();
this.GroupeSecurite=new HashSet();
this.vehicleCompagnie=new HashSet();
this.Employe1=新的HashSet();

Visual Studio非常聪明,几乎可以在所有东西中重命名它们,除了在我的Entities.edmx、Views和我的元数据中。我非常小心地处理了它,现在,所有东西都工作得很好。我仍然不明白为什么我可以编辑我的员工…

看起来像是依赖性问题,而你的外键不能为null,这意味着在添加新记录时必须提供键,但可以使外键为空仅用于测试?似乎所有外键整数属性都应该使用
null
type,例如
public int?IdTitre{get;set;}
。当包含值类型FK属性的对象映射到另一个实体,并且错误地将FK属性设置为默认值(0)而不是
null
,导致EF在另一个不存在的实体中找到“0”的PK时,通常会发生此错误。
// GET: Employes/Create
    //[AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
    public ActionResult Create()
    {
        var employeView = new EmployeVM();

        //Population pour les ListBoxFor
        var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
        ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdTelephoneCellulaire.ToString()
        });
        var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
        ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdEquipementInfo.ToString()
        });
        var allGroupeSecuriteList = db.GroupeSecurite.ToList();
        ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdGroupeSecurite.ToString()
        });
        var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
        ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdAccesApplicatif.ToString()
        });
        var allCleBatimentList = db.CleBatiment.ToList();
        ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdCleBatiment.ToString()
        });
        var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
        ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
        {
            Text = o.DescriptionVehicule,
            Value = o.IdVehiculeCompagnie.ToString()
        });

        //Zero-or-One-to-Many relationships
        List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
        ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");

        List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
        ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");

        List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
        ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");

        List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
        ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");

        List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
        ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");

        List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
        ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");

        return View();
    }

    // POST: Employes/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, 
    // for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(EmployeVM employeView)
    {
        if (!ModelState.IsValid)
        {
            foreach (var obj in ModelState.Values)
            {
                foreach (var error in obj.Errors)
                {
                    if (!string.IsNullOrEmpty(error.ErrorMessage))
                        System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
                }
            }
        }

        if (ModelState.IsValid)
        {
            var employeToAdd = db.Employe
                .Include(e => e.TelephoneCellulaire1)
                .Include(e => e.EquipementInfo)
                .Include(e => e.GroupeSecurite1)
                .Include(e => e.AccesApplicatif1)
                .Include(e => e.CleBatiment1)
                .Include(e => e.VehiculeCompagnie1)
                .First();

            if (TryUpdateModel(employeToAdd, "Employe", new string[] { "IdEmploye", "NomEmploye", "PrenomEmploye", "IdTitre", "IdDepartement", "IdSuperviseur", "DateEmbauche", "DateDepart", "StatutEmploye", "IdEmployeur", "IdLocalisation", "Langue", "CarteAcces", "TelephoneCellulaire", "IdTelephoneBureau", "CarteAffaire", "EquipementInformatique", "AdresseCourriel", "GroupeSecurite", "AccesApplicatif", "CodeAlarme", "CleBatiment", "VehiculeCompagnie", "DateNaissance", "IsSuperviseur", "IsActif" }))
            {
                var updatedTelephoneCellulaires = new HashSet<int>(employeView.SelectedTelephoneCellulaires);
                var updatedEquipementInformatiques = new HashSet<int>(employeView.SelectedEquipementInformatiques);
                var updatedGroupeSecurites = new HashSet<int>(employeView.SelectedGroupeSecurites);
                var updatedAccesApplicatifs = new HashSet<int>(employeView.SelectedAccesApplicatifs);
                var updatedCleBatiments = new HashSet<int>(employeView.SelectedCleBatiments);
                var updatedVehiculeCompagnies = new HashSet<int>(employeView.SelectedVehiculeCompagnies);

                //Prochaine ligne db.TelephoneCellulaire1 !!! ou db.TelephoneCellulaireActif ???  Check readonly
                foreach (TelephoneCellulaire telephone in db.TelephoneCellulaire)
                {
                    if (!updatedTelephoneCellulaires.Contains(telephone.IdTelephoneCellulaire))
                    {
                        employeToAdd.TelephoneCellulaire1.Remove(telephone);
                    }
                    else
                    {
                        employeToAdd.TelephoneCellulaire1.Add(telephone);
                    }
                }
                foreach (EquipementInfo equipement in db.EquipementInfo)
                {
                    if (!updatedEquipementInformatiques.Contains(equipement.IdEquipementInfo))
                    {
                        employeToAdd.EquipementInfo.Remove(equipement);
                    }
                    else
                    {
                        employeToAdd.EquipementInfo.Add(equipement);
                    }
                }
                foreach (GroupeSecurite groupe in db.GroupeSecurite)
                {
                    if (!updatedGroupeSecurites.Contains(groupe.IdGroupeSecurite))
                    {
                        employeToAdd.GroupeSecurite1.Remove(groupe);
                    }
                    else
                    {
                        employeToAdd.GroupeSecurite1.Add(groupe);
                    }
                }
                foreach (AccesApplicatif acces in db.AccesApplicatif)
                {
                    if (!updatedAccesApplicatifs.Contains(acces.IdAccesApplicatif))
                    {
                        employeToAdd.AccesApplicatif1.Remove(acces);
                    }
                    else
                    {
                        employeToAdd.AccesApplicatif1.Add(acces);
                    }
                }
                foreach (CleBatiment cle in db.CleBatiment)
                {
                    if (!updatedCleBatiments.Contains(cle.IdCleBatiment))
                    {
                        employeToAdd.CleBatiment1.Remove(cle);
                    }
                    else
                    {
                        employeToAdd.CleBatiment1.Add(cle);
                    }
                }
                foreach (VehiculeCompagnie vehicule in db.VehiculeCompagnie)
                {
                    if (!updatedVehiculeCompagnies.Contains(vehicule.IdVehiculeCompagnie))
                    {
                        employeToAdd.VehiculeCompagnie1.Remove(vehicule);
                    }
                    else
                    {
                        employeToAdd.VehiculeCompagnie1.Add(vehicule);
                    }
                }
            }
            db.Employe.Add(employeToAdd);
            db.SaveChanges();
            return RedirectToAction("Index");
        }                    

        var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
        ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdTelephoneCellulaire.ToString()
        });
        var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
        ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdEquipementInfo.ToString()
        });
        var allGroupeSecuriteList = db.GroupeSecurite.ToList();
        ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdGroupeSecurite.ToString()
        });
        var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
        ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdAccesApplicatif.ToString()
        });
        var allCleBatimentList = db.CleBatiment.ToList();
        ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
        {
            Text = o.Description,
            Value = o.IdCleBatiment.ToString()
        });
        var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
        ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
        {
            Text = o.DescriptionVehicule,
            Value = o.IdVehiculeCompagnie.ToString()
        });

        //Zero-or-One-to-Many relationships
        List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
        ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");

        List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
        ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");

        List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
        ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");

        List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
        ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");

        List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
        ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");

        List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
        ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");

        return View(employeView);
    }
        <div class="form-group">
        @Html.LabelFor(model => model.AllEquipementInformatiques, "Équipements informatiques", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.ListBoxFor(model => model.SelectedEquipementInformatiques, (IEnumerable<SelectListItem>)ViewBag.AllEquipementInformatiques, new { @class = "form-control" })
        </div>
    </div>
CREATE TABLE [dbo].[Employe_GroupeSecurite] (
[IdEmploye]        INT NOT NULL,
[IdGroupeSecurite] INT NOT NULL,
PRIMARY KEY CLUSTERED ([IdEmploye] ASC, [IdGroupeSecurite] ASC),
CONSTRAINT [FK_Employe_GroupeSecurite_Employe] FOREIGN KEY ([IdEmploye]) REFERENCES [dbo].[Employe] ([IdEmploye]),
CONSTRAINT [FK_Employe_GroupeSecurite_GroupeSecurite] FOREIGN KEY ([IdGroupeSecurite]) REFERENCES [dbo].[GroupeSecurite] ([IdGroupeSecurite])
public Employe()
{
    this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
    this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
    this.CleBatiment1 = new HashSet<CleBatiment>();
    this.EquipementInfo = new HashSet<EquipementInfo>();
    this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
    this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
    this.Employe1 = new HashSet<Employe>();
}
this.AccesApplicatif = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire = new HashSet<TelephoneCellulaire>();
this.CleBatiment = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();