You must Sign In to post a response.
  • Category: LINQ

    How to make delete row from table using linq

    In my Relation i have two tables relation (one to many)

    table country

    Id (primary key)

    Countryname

    table City

    Id (primary key)

    Cityname

    Countryid (forign key)

    I have controller City have the following function

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using LinqProject.Models;
    namespace LinqProject.Controllers
    {
    public class CityController : Controller
    {
    mytaskdbEntities db = new mytaskdbEntities();

    // GET: City
    public ActionResult List()
    {
    return View(db.Cities.ToList());
    }

    and in view of List as following

    <body>
    <div>
    <table>
    @foreach (var item in Model)
    {
    <tr><td>@item.Cityname</td><td>@item.Country.Countryname</td></tr>
    }
    </table>
    </div>
    </body>

    What i need actually adding delete button to view of list of city

    and i can delete city when click button delete

    how to do deleting record by linq

    the final result as following

    USA NEWYORK DELETEBUTTON

    USA WASHINTON DELETEBUTTON

    FRANCE PARIS DELETEBUTTON

    when click delete button for row USA NEWYORK it will delete

    and remaining two record

    USA WASHINTON DELETEBUTTON

    FRANCE PARIS DELETEBUTTON
  • #767551
    To delete a row in the database
    1. Query the database for the row to be deleted.
    2. Call the DeleteOnSubmit method.
    3. Submit the change to the database.
    see below snippet

    // Query the database for the rows to be deleted.
    var deleteOrderDetails =
    from details in db.OrderDetails
    where details.OrderID == 11000
    select details;

    foreach (var detail in deleteOrderDetails)
    {
    db.OrderDetails.DeleteOnSubmit(detail);
    }

    try
    {
    db.SubmitChanges();
    }
    catch (Exception e)
    {
    Console.WriteLine(e);
    // Provide for exceptions.
    }


    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #767568
    Hi,

    You can delete database entry by using below lamda expression.


    foreach(Countryclass ctr in lstCountries)
    {
    var ctryDelete= from ctry in country
    where ctry.CountryId == ctr.Country.Id
    select ctry;

    obj.DeleteonSubmit(ctryDelete);
    obj.SubmitChanges();
    }


    Hope this helps you....

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/


Sign In to post your comments