I'm having problems updating entities with EF6 and MySql.
This is part of the code:
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;
}
}
}
And I used it with something like that:
var _repositorio = new Repositorio<MyEntity>(myContext);
var myEntity = _repositorio.GetById(13);
myEntity.Name = "Mooo";
_repositorio.Update(myEntity);
It doesn't throw any exception, but the data has no changes.
The Insert() method works perfect.
Any idea about this?
PS: I'm using MySql.Data.Entities from NuGet Package Installer, and it includes EF 6.0.0, MySql.Data 6.8.3.0 and MySql.Data.Entity.EF6 6.8.3.0.
haha, ah ok I see your problem.. change your update method to this:
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;
}
}
Also, have a look at using the UnitOfWork pattern along with the repository pattern, you will need it.
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.