none
ASP MVC 4.0 exception ENtityFramework context.savechanges() RRS feed

  • Question

  • Bonjour,

    lorsque je souhaite créer un nouvel objet dans ma méthode create de mon controller et que je le sauve, entity framework me lance une exception.

    voici le code de mon create :

    Pour info: je passe ces paramètres de cette manière et non par un objet de type Fiches car sinon le modelState est toujours invalide a cause des relations many to many (liste de checkbox que j'ai du implémenter)

    ' POST: Fiches/Create
            <HttpPost()>
            Function Create(nomenclatureId As Long, NatureTravaux() As Long, natureAcquisitions() As Long, NatureMaintenance() As Long, NatureGeneral() As Long, SiAutre As String, Libelle As String, _
                            Description As String, DemandeurId As Long, Montant As Double, EstSubsidie As Boolean, PourcentageId As Long, DureeId As Long, DateCollege As DateTime, _
                            ProjetId As Long, PrioriteId As Long, IsAutreServiceImplique As Boolean, Services() As Long, Contraintes() As Long, Responsable As String, Optional NumeroProjet As Long = 0) As ActionResult ' ByVal fiche as Fiches
                Try
                    If Not ModelState.IsValid Then
                        Return RedirectToAction("Create", "Fiches")
                    Else
                        Dim uneFiche As Fiches = New Fiches()
                        uneFiche.NomenclatureId = nomenclatureId
     
                        If NatureTravaux IsNot Nothing Then
                            For Each item As Long In NatureTravaux
                                uneFiche.NatureTravaux.Add(context.NatureTravaux.FirstOrDefault(Function(x) x.NatureTravauxId = item))
                            Next
                        End If
     
                        If natureAcquisitions IsNot Nothing Then
                            For Each item As Long In natureAcquisitions
                                uneFiche.NatureAcquisitions.Add(context.NatureAcquisitions.FirstOrDefault(Function(x) x.NatureAcquisitionId = item))
                            Next
                        End If
     
                        If NatureMaintenance IsNot Nothing Then
                            For Each item As Long In NatureMaintenance
                                uneFiche.NatureMaintenances.Add(context.NatureMaintenances.FirstOrDefault(Function(x) x.NatureMaintenanceId = item))
                            Next
                        End If
     
                        If NatureGeneral IsNot Nothing Then
                            For Each item As Long In NatureGeneral
                                uneFiche.NatureGenerales.Add(context.NatureGenerales.FirstOrDefault(Function(x) x.NatureGeneralId = item))
                            Next
                        End If
                        If Not String.IsNullOrEmpty(SiAutre) Then
                            uneFiche.SiAutre = SiAutre
                        End If
                        uneFiche.Libelle = Libelle
     
                        If Not String.IsNullOrEmpty(Description) Then
                            uneFiche.Description = Description
                        End If
                        uneFiche.DemandeurId = DemandeurId
                        uneFiche.Montant = Montant
     
                        If EstSubsidie Then
                            uneFiche.EstSubsidie = EstSubsidie
                            uneFiche.PourcentageId = PourcentageId
                        Else
                            uneFiche.EstSubsidie = False
                        End If
                        uneFiche.DureeId = DureeId
                        uneFiche.DateCollege = DateCollege
                        uneFiche.ProjetId = ProjetId
                        uneFiche.PrioriteId = PrioriteId
     
                        If IsAutreServiceImplique Then
                            uneFiche.IsAutreServiceImplique = IsAutreServiceImplique
                            If Services IsNot Nothing Then
                                For Each item As Long In Services
                                    uneFiche.Services1.Add(context.Services.FirstOrDefault(Function(x) x.ServiceId = item))
                                Next
                            Else
                                RedirectToAction("Create")
                            End If
                        Else
                            uneFiche.IsAutreServiceImplique = False
                        End If
     
                        If Contraintes IsNot Nothing Then
                            For Each item As Long In Contraintes
                                uneFiche.Contraintes.Add(context.Contraintes.FirstOrDefault(Function(x) x.ContrainteId = item))
                            Next
                        End If
     
                        uneFiche.Responsable = Responsable
                        If NumeroProjet > 0 Then
                            uneFiche.NumeroProjet = NumeroProjet
                        End If
     
                        context.Fiches.Add(uneFiche)
                        context.SaveChanges()
                    End If
     
                    Return RedirectToAction("Index")
                Catch
                    Return View("Erreur")
                End Try
            End Function


    voici la vue qui lui est liée :

    @ModelType Fiche_Budgetaire.Fiches
    @Code
        ViewData("Title") = "Create"
    End Code
     
    <h2>Create</h2>
     
    @Using (Html.BeginForm())
        @Html.AntiForgeryToken()
     
        @<div class="form-horizontal">
            <h4>Fiches</h4>
            <hr />
            @Html.ValidationSummary(True, "", New With {.class = "text-danger"})
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NomenclatureId, "Nomenclature", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.NomenclatureId, New SelectList(CType(ViewBag.Nomenclatures, List(Of Nomenclatures)), "NomenclatureId", "Libelle"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.NomenclatureId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NatureTravaux, "Nature TRAVAUX", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.NatureTravaux, List(Of NatureTravaux))
                    @<div>
                        <label>
                            <input type="checkbox" name="NatureTravaux" value="@item.NatureTravauxId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NatureAcquisitions, "Nature ACQUISITION", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.NatureAcquisition, List(Of NatureAcquisitions))
                    @<div>
                        <label>
                            <input type="checkbox" name="NatureAcquisitions" value="@item.NatureAcquisitionId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NatureMaintenances, "Nature MAINTENANCE", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.NatureMaintenance, List(Of NatureMaintenances))
                    @<div>
                        <label>
                            <input type="checkbox" name="NatureMaintenance" value="@item.NatureMaintenanceId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NatureGenerales, "Nature GÉNÉRALE", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.NatureGenerales, List(Of NatureGenerales))
                    @<div>
                        <label>
                            <input type="checkbox" name="NatureGeneral" value="@item.NatureGeneralId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
        <div class="form-group">
            @Html.LabelFor(Function(model) model.SiAutre, "Si ""Autres"", précisez", htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.TextAreaFor(Function(model) model.SiAutre, New With {.htmlAttributes = New With {.class = "form-control"}})
                @Html.ValidationMessageFor(Function(model) model.SiAutre, "", New With {.class = "text-danger"})
            </div>
        </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Libelle, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Libelle, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Libelle, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Description, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Description, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Description, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.DemandeurId, "Demandeur", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.DemandeurId, New SelectList(CType(ViewBag.Demandeurs, List(Of Demandeurs)), "DemandeurId", "Libelle"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.DemandeurId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Montant, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Montant, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Montant, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.EstSubsidie, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(Function(model) model.EstSubsidie)
                        @Html.ValidationMessageFor(Function(model) model.EstSubsidie, "", New With {.class = "text-danger"})
                    </div>
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.PourcentageId, "Pourcentage", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.PourcentageId, New SelectList(CType(ViewBag.Pourcentages, List(Of Pourcentages)), "PourcentageId", "valeur"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.PourcentageId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.DureeId, "Durée", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.DureeId, New SelectList(CType(ViewBag.Durees, List(Of Durees)), "DureeId", "Libelle"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.DureeId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.DateCollege, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.DateCollege, New With {.htmlAttributes = New With {.class = "datepicker form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.DateCollege, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.ProjetId, "Projet", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.ProjetId, New SelectList(CType(ViewBag.Projets, List(Of Projets)), "ProjetId", "Type"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.ProjetId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.NumeroProjet, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.NumeroProjet, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.NumeroProjet, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.PrioriteId, "Priorité", htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.DropDownListFor(Function(x) x.PrioriteId, New SelectList(CType(ViewBag.Priorites, List(Of Priorites)), "PrioriteId", "Libelle"), htmlAttributes:=New With {.class = "form-control"})
                    @Html.ValidationMessageFor(Function(model) model.PrioriteId, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.IsAutreServiceImplique, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(Function(model) model.IsAutreServiceImplique)
                        @Html.ValidationMessageFor(Function(model) model.IsAutreServiceImplique, "", New With {.class = "text-danger"})
                    </div>
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.ServiceId, "Service", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.Services, List(Of Services))
                    @<div>
                        <label>
                            <input type="checkbox" name="Services" value="@item.ServiceId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Contraintes, "Contraintes de mise en oeuvre", htmlAttributes:=New With {.class = "control-label col-md-2"})
                @For Each item In CType(ViewBag.Contraintes, List(Of Contraintes))
                    @<div>
                        <label>
                            <input type="checkbox" name="Contraintes" value="@item.ContrainteId" /> <span class="NormalFontWeight">@item.Libelle</span>
                        </label>
                    </div>
                Next
            </div>
     
            <div class="form-group">
                @Html.LabelFor(Function(model) model.Responsable, htmlAttributes:=New With {.class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(Function(model) model.Responsable, New With {.htmlAttributes = New With {.class = "form-control"}})
                    @Html.ValidationMessageFor(Function(model) model.Responsable, "", New With {.class = "text-danger"})
                </div>
            </div>
     
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Nouvelle demande" class="btn btn-default" />
                </div>
            </div>
        </div>
    End Using
     
    <div>
        @Html.ActionLink("Retour accueil", "Index")
    </div>
     
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    voici l'exception retournée par EntityFramework :

    L'instruction INSERT est en conflit avec la contrainte FOREIGN KEY "FK_dbo.Fiches_dbo.Pourcentages_PourcentageId". Le conflit s'est produit dans la base de données "FicheBudgetaireContext", table "dbo.Pourcentages", column 'PourcentageId'. L'instruction a été arrêtée.

    Dans le doute, voici le code de la classe Fiches :

    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel.DataAnnotations
    Imports System.ComponentModel.DataAnnotations.Schema
    Imports System.Data.Entity.Spatial
     
    Partial Public Class Fiches
        Public Sub New()
            Contraintes = New HashSet(Of Contraintes)()
            NatureAcquisitions = New HashSet(Of NatureAcquisitions)()
            NatureGenerales = New HashSet(Of NatureGenerales)()
            NatureMaintenances = New HashSet(Of NatureMaintenances)()
            NatureTravaux = New HashSet(Of NatureTravaux)()
            Services1 = New HashSet(Of Services)()
        End Sub
     
        <Key>
        Public Property FicheId As Long
     
        <Required>
        <StringLength(150)>
        Public Property Libelle As String
     
        <DataType(DataType.MultilineText)>
        Public Property Description As String
     
        Public Property Montant As Double
     
        <Display(Name:="Subside")>
        Public Property EstSubsidie As Boolean
     
        <DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:dd/MM/yyyy}")>
        <Display(Name:="Date")>
        Public Property DateCollege As DateTime
     
        <Display(Name:="Autres services impliqués")>
          Public Property IsAutreServiceImplique As Boolean
     
        <Required>
        Public Property Responsable As String
     
        Public Property NomenclatureId As Long
     
        Public Property DemandeurId As Long
     
        Public Property PourcentageId As Long
     
        Public Property DureeId As Long
     
        Public Property ProjetId As Long
     
        Public Property PrioriteId As Long
     
        Public Property ServiceId As Long
     
        <StringLength(50)>
          <Display(Name:="Si poursuite, indiquez le numéro de projet")>
        Public Property NumeroProjet As String
     
        Public Property SiAutre As String
     
        Public Overridable Property Demandeurs As Demandeurs
     
        Public Overridable Property Durees As Durees
     
        Public Overridable Property Nomenclatures As Nomenclatures
     
        Public Overridable Property Pourcentages As Pourcentages
     
        Public Overridable Property Priorites As Priorites
     
        Public Overridable Property Projets As Projets
     
        Public Overridable Property Services As Services
     
        Public Overridable Property Contraintes As ICollection(Of Contraintes)
     
        Public Overridable Property NatureAcquisitions As ICollection(Of NatureAcquisitions)
     
        Public Overridable Property NatureGenerales As ICollection(Of NatureGenerales)
     
        Public Overridable Property NatureMaintenances As ICollection(Of NatureMaintenances)
     
        Public Overridable Property NatureTravaux As ICollection(Of NatureTravaux)
     
        Public Overridable Property Services1 As ICollection(Of Services)
    End Class
    

    uriez-vous une idée car là je sèche 
    D'avance merci.

    {"L'instruction INSERT est en conflit avec la contrainte FOREIGN KEY "FK_dbo.Fiches_dbo.Pourcentages_PourcentageId". Le conflit s'est produit dans la base de données "FicheBudgetaireContext", table "dbo.Pourcentages", column 'PourcentageId'.
    L'instruction a été arrêtée."}
    {"L'instruction INSERT est en conflit avec la contrainte FOREIGN KEY "FK_dbo.Fiches_dbo.Pourcentages_PourcentageId". Le conflit s'est produit dans la base de données "FicheBudgetaireContext", table "dbo.Pourcentages", column 'PourcentageId'.
    L'instruction a été arrêtée."}
    {"L'instruction INSERT est en conflit avec la contrainte FOREIGN KEY "FK_dbo.Fiches_dbo.Pourcentages_PourcentageId". Le conflit s'est produit dans la base de données "FicheBudgetaireContext", table "dbo.Pourcentages", column 'PourcentageId'.
    L'instruction a été arrêtée."}
    {"L'instruction INSERT est en conflit avec la contrainte FOREIGN KEY "FK_dbo.Fiches_dbo.Pourcentages_PourcentageId". Le conflit s'est produit dans la base de données "FicheBudgetaireContext", table "dbo.Pourcentages", column 'PourcentageId'.
    L'instruction a été arrêtée."}
    mercredi 1 août 2018 09:51

Toutes les réponses

  • Bonsoir Laubry,

    apparement lors de l'ajout d'un l'enregistrement ou bien la valeur PourcentageId ne correspond a aucun enreistrement sur la table Pourcentages, ou bien tout simplement la valeur PourcentageId est a 0, donc si tu peux verifier de ce coter je pense que serrais efficcace.

    Good Coding;

    mercredi 17 octobre 2018 22:32