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.
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);
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.