My goal is to make a deletion function that uses LINQ to delete a record from a database table by finding the id the user inputs that matches the record’s primary key.
-
MyDBEntitiesClass is the argument that the function needs to be passed which tells it what DataTable to search.
-
IDontKnowWhatType is the type I’m asking for help in determining.
-
MyPrimaryKey needs to be replaced with something that references the primary key of MyDBEntitiesClass.
-
TestDatabaseEntities is the name of the connection string created by generating an entity model from my existing SQL server database.
public static void DeleteFrom(IDontKnowWhatType MyDBEntitiesClass)
{
var dbEntities = new TestDatabaseEntities();
//Prompt the user for an ID
Console.WriteLine("Select ID for deletion.");
// save the ID to IDtoMark
int IDtoMark = int.Parse(Console.ReadLine());
try
{
// return a single record that matches IDtoMark
MyDbEntitiesClass x = dbEntities.MyDbEntitiesClass.Single(x => x.myPrimaryKey == IDtoMark);
//Remove the marked record, and save changes
dbEntities.MyDbEntitiesClass.Remove(x);
dbEntities.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You can achieve this by implementing Repository Pattern.
I guess you are using entity framework. For that you have generic class.