Reputation: 1070
Consider the situation: I want delete and update items from Database using Entity Framework. I want to achieve it generically using LINQ to entities provided the Database context, ID of row to be deleted, column to be updated and the value to which it should be updated are already available with us.
How can i do it generically. Please advice. Thanks in advance.
Upvotes: 0
Views: 1261
Reputation: 395
You can use DAO object like Repository between DB and your code, some like this
public class Dao<T> : where T:class {
internal virtual DbSet<T> EntitySet {
get {
return DB.Set<T>();
}
}
public void DeleteById(int id) {
T instance = FindById(id);
Delete(instance);
}
public void Update(T instance) {
DB.Entry(instance).State = EntityState.Modified;
DB.SaveChanges();
}
}
And use code
Dao<someClass> daoClass = new Dao<someClass>(new dbContext());
daoClass.DeleteById(5);
daoClass.Update(someClass);
Upvotes: 1
Reputation: 1803
Good Day, I'm not sure about the question but I'll give an idea on how to do update and delete
Update
using (var db = new DbContext())
{
var tobeupdatedrow = db.TableNames.FirstOrDefault(b => b.Id== Id);
if (tobeupdatedrow != null)
{
tobeupdatedrow.tobeupdatedcolumn = "Some new value";
db.SaveChanges();
}
}
Delete
using (var db = new DbContext())
{
var tobedeletedrow = db.TableNames.FirstOrDefault(b => b.Id== Id);
if (tobedeletedrow != null)
{
db.TableNames.Remove(tobedeletedrow);
db.SaveChanges();
}
}
Upvotes: 0