实体框架删除

时间:2014-05-27 09:46:48

标签: entity-framework

我想从带有Entity framework

的Sql server中删除数据

这是我的ASP.net表单:

    

         <p> 
        <asp:Label ID="Label_votre_societe" runat="server" Text="Votre société :" CssClass="plabel_large"></asp:Label>
    </p>
    <p class="plabel">
        <asp:Label ID="Label_numero_siret" runat="server"  Text="N° SIRET :"></asp:Label>
        <asp:TextBox ID="TextBox_numero_siret" CssClass="ptextbox" runat="server" MaxLength="14" ></asp:TextBox>

        <asp:RegularExpressionValidator id="validat_siret" runat="server" ErrorMessage="Veuillez rentrer un numero de siret valable" ControlToValidate="Textbox_numero_siret" ValidationExpression=".{14}.*"  ></asp:RegularExpressionValidator>

       <p>  <asp:Label ID="label_ou" runat="server" CssClass="plabel" Text="OU"></asp:Label> </p>
        </p>
    <p class="plabel">
        <asp:Label ID="Label_numero_telephone" runat="server" Text="N° Telephone :"></asp:Label>

        <asp:TextBox ID="TextBox_numero_telephone" runat="server" MaxLength="12"  ></asp:TextBox>

        <asp:RegularExpressionValidator ID="validator_number" runat="server" ControlToValidate="Textbox_numero_telephone" ErrorMessage="Veuillez rentrer un numéro de telephone correct" ValidationExpression="^(0|\+33)[1-9]([-. ]?[0-9]{2}){4}$"> </asp:RegularExpressionValidator>

        <asp:CustomValidator ID="cvMobilePhone" runat="server" ErrorMessage="Veuillez renseigner un numero de siret ou telephone" ClientValidationFunction="Validate(sender, args)" ValidateEmptyText="true"></asp:CustomValidator>



</p>
    <p class="plabel_large">
        <asp:Label ID="Label_Vous" runat="server" Text="Vous :"></asp:Label>
    </p>
    <p class="plabel">
        <asp:Label ID="Label_adressemail" runat="server" Text="Votre adresse mail :"></asp:Label>
        <asp:TextBox ID="TextBox_adressemail" CssClass="ptextbox" type="Email" runat="server"  ></asp:TextBox>
    </p>

Clients objDel = new Clients
            {
                Numero_siret = TextBox_numero_siret.Text,
                Numero_telephone = TextBox_numero_telephone.Text,
                Adresse_mail = TextBox_adressemail.Text,
                Logiciel = DropDownList_choixlogiciel.SelectedValue,

            };
            db.Clients.Remove(objDel);
        db.SaveChanges();

我有一个错误:InvalidOperationException:无法删除对象

2 个答案:

答案 0 :(得分:0)

您的对象未附加到上下文,请尝试通过db.Client.Select(x => x.SomeProp == "someValue")而不是new来获取。

答案 1 :(得分:0)

在EntityFramework 6中,您可以使用.RemoveRange()删除条目。

示例:

using (DbContextTransaction transaction = this.dataContext.Database.BeginTransaction())
                    {

db.Client.RemoveRange(db.Client.Where(x => SomeState == "somevalue"));

                        this.dataContext.SaveChanges();
                        transaction.Commit();
                    }