我在使用EF6和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)
哈哈啊,好吧,我看到了你的问题..把你的更新方法更改为:
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模式以及存储库模式,您将需要它。