how to make delete row from table using linq [Resolved]

Posted by Ahmedsa under LINQ on 8/14/2016 | Points: 10 | Views : 188 | Status : [Member] | Replies : 2
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





Responses

Posted by: Rajnilari2015 on: 8/15/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Hi,
In your case you have to delete the city. You can do something as under

using (var context = new YourDBContext())
{
var cityRecord = context.Cities.Find(cityID);
context.Cities.Remove(cityRecord);
context.SaveChanges();
}


Let us know in case you have any further doubts.

--
Thanks & Regards,
RNA Team

Ahmedsa, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bhuvanesh6 on: 8/18/2016 [Member] Starter | Points: 25

Up
0
Down
What Raj Suggested is good solution,

This will help you to remove all the City or common records at once,

cityList.RemoveAll(x => x.CityName == "Patna");


Bhuvan

Ahmedsa, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response