我正在尝试创建一个GenericDAO来处理我的实体,一切都没问题,除了更新方法它没有更新实体,并且没有例外。
我该如何解决?
尝试
GenericDAO
public class GenericDAO<T> : IPersist<T> where T : class {
private DatabaseContext context;
public GenericDAO() {
context = new DatabaseContext();
}
public Boolean insert(T obj) {
try{
context.Set<T>().Add(obj);
context.SaveChanges();
return true;
}catch(Exception e){
Debug.WriteLine("Insert error: " + e.InnerException.Message);
}
return false;
}
public Boolean update(T obj) {
try{
context.Entry<T>(obj).State = System.Data.Entity.EntityState.Modified;
return true;
}catch (Exception e){
Debug.WriteLine("Update error: " + e.InnerException.Message);
}
return false;
}
public Boolean delete(T obj) {
try{
context.Set<T>().Remove(obj);
context.SaveChanges();
return true;
}catch (Exception e){
Debug.WriteLine("Delete error: " + e.InnerException.Message);
}
return false;
}
public T findObject(long id) {
return context.Set<T>().Find(id);
}
public IQueryable<T> GetAll(){
IQueryable<T> query = context.Set<T>();
return query;
}
}
ProdutoDAO
class ProdutoDAO : GenericDAO<Produto>{}
是
private void button1_Click(object sender, EventArgs e){
ProdutoDAO dao = new ProdutoDAO();
Produto p = dao.findObject(1); //get the object
p.descricao = "Bottle Water";
p.dtCad = DateTime.Now;
p.valor = 1.00m;
//update object
if (dao.update(p)) {
Console.WriteLine("update ok!");
}else{
Console.WriteLine("update error");
}
}