[英]Entity Framework and MySql updating entity
我在使用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软件包安装程序中的MySql.Data.Entities,其中包括EF 6.0.0,MySql.Data 6.8.3.0和MySql.Data.Entity.EF6 6.8.3.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模式与存储库模式一起使用,您将需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.