I have a problem with EntityFramework-6, I am trying to create a "disconnected" entity to simply save the changes of the fields that I want.
My context (DataContext.cs) has a member named Demos, and that entity type (Demo.cs) is derived from a class called ModelBase.
In my database, my "Demo" table is created as such as I have it in the DataContent.
When saving the changes, EF, only saves the changes to the Demo.cs class and not those inherited from ModelBase.cs.
This is the code that fails:
using (var contexto = new DataContext())
{
// Creo la entidad.
var demo = new Demo { Id = 1 };
// Lo agrego al control de cambios.
context.Demos.Attach(demo);
// Este cambio si lo actualiza.
obj.Nombre = "Carlos";
// Este cambio NO LO ACTUALIZA.
obj.Modified = DateTime.Now;
context.SaveChanges();
}
This other example does work:
using (var contexto = new DataContext())
{
// Creo la entidad.
var demo = new Demo { Id = 1 };
// Lo agrego al control de cambios.
context.Demos.Attach(demo);
// Este cambio si lo actualiza.
demo.Nombre = "Carlos";
// Este cambio si lo actualiza si lo especifico explicitamente.
demo.Modified = DateTime.Now;
context.Entry(demo).Property(x => x.Modified).IsModified = true;
context.SaveChanges();
}
DataContext
public class DataContext : DbContext
{
public DbSet<Models.Demo> Demos { get; set; }
}
Demo.cs
public class Demo : ModelBase
{
public string Nombre { get; set; }
public string Apellidos { get; set; }
}
ModelBase.cs
public class ModelBase : Core.DataAccessLayer.IModelBase
{
/// <summary>
/// Crea una nueva instancia de <see cref="ModelBase"/>.
/// </summary>
public ModelBase()
{
this.Created = DateTime.Now;
this.Modified = DateTime.Now;
}
/// <summary>
/// Obtiene o establece el identificador de un registro.
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
/// Obtiene o establece la fecha de creación.
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// Obtiene o establece la fecha de modificación.
/// </summary>
public DateTime Modified { get; set; }
}
Edit:
I marked the ModelBase fields as "virtual", and now if you update it, however, it is not constant.
In some cases, execute this query:
exec sp_executesql N'UPDATE [dbo].[Demoes]
SET [Nombres] = @0, [Modified] = @1
WHERE ([Id] = @2)
',N'@0 nvarchar(max) ,@1 datetime2(7),@2 int',@0=N'25/05/2016 9:02:18',@1='2016-05-25 09:02:18.7027657',@2=1
And on other occasions this:
exec sp_executesql N'UPDATE [dbo].[Demoes]
SET [Nombres] = @0
WHERE ([Id] = @1)
',N'@0 nvarchar(max) ,@1 int',@0=N'25/05/2016 9:02:14',@1=1