2014-03-07 221 views
0

我在使用EF6和MySql更新实体时遇到问题。实体框架和MySql更新实体

这是部分代码:

public partial class Repositorio<T> : IRepositorio<T> where T : EntidadBase 
{ 
    private readonly IDbContext _contexto; 
    private IDbSet<T> _entidades; 

    public Repositorio(IDbContext contexto) 
    { 
     this._contexto = contexto; 
    } 

    private IDbSet<T> Entidades 
    { 
     get 
     { 
      if (_entidades == null) 
       _entidades = _contexto.Set<T>(); 
      return _entidades; 
     } 
    } 

    public void Insert(T entity) 
    { 
     try 
     { 
      if (entity == null) 
       throw new ArgumentNullException("entity"); 

      this.Entidades.Add(entity); 

      this._contexto.SaveChanges(); 
     } 
     catch (Exception dbEx) 
     { 
      throw dbEx 
     } 
    } 


    public void Update(T entidad) 
    { 
     try 
     { 
      if (entidad == null) 
       throw new ArgumentNullException("entidad"); 

      this._contexto.SaveChanges(); 
     } 
     catch (Exception dbEx) 
     { 
      throw dbEx; 
     } 
    } 
} 

和我一起类似的东西,用它:

var _repositorio = new Repositorio<MyEntity>(myContext); 
var myEntity = _repositorio.GetById(13); 

myEntity.Name = "Mooo"; 

_repositorio.Update(myEntity); 

它不抛出任何异常,但数据没有变化。

Insert()方法完美。

对此有何想法? PS:我使用NuGet Package Installer的MySql.Data.Entities,它包括EF 6.0.0,MySql.Data 6.8.3.0和MySql.Data.Entity.EF6 6.8.3.0。

+0

您的示例代码显示了插入方法,但对回购的调用调用了更新方法。你正在调用的更新方法的代码是什么? –

+0

你好尼尔。您必须在存储库的代码块中向下滚动以查看它:-) – dank0ne

+0

请考虑删除此存储库层。它只会麻烦你。首先,你只能更新单个数据实例。如果你想在一次交易中保存很多对象呢?请参阅[此问题](http://stackoverflow.com/q/21758807/861716)以获得有关该主题的深入讨论。和[这一个](http://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884)可能会说服你使用'DbSet '和'DbContext'直接。 –

回答

0

哈哈,啊好,我看到您的问题..改变你的更新方法,以这样的:

public void Update(T entidad) 
    { 
     try 
     { 
      if (entidad == null) 
       throw new ArgumentNullException("entidad"); 

      _contexto.Entry(entidad).State = System.Data.EntityState.Modified; 
      this._contexto.SaveChanges(); 
     } 
     catch (Exception dbEx) 
     { 
      throw dbEx; 
     } 
    } 

而且,看看使用的UnitOfWork模式与存储库模式一起,你会需要它。

+0

但是此时实体已经应该是'Modified'(假设'GetById'将它附加到存储库的上下文中)。 –