Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework : Update affecting Object

I'm having an issue with the EF Update method.

I have an object that contains mutliple informations and other complex objects For instance when I debug my object.otherObject contains data.

Then I update it with the following line :

_dbContext.Update(object);

The problem being that after the update call, my object.otherObject loses its value and gets to null.

When trying with a different operation (User interface action) and the same object (different values) I don't meet that issue.

From my understanding of EF update, it should mark the object as modified but leave it intact.

EDIT :

My mapping file is :

internal class ObjectConfiguration: EntityTypeConfiguration<Object>
{
    public ObjectConfiguration()
    {
        ToTable("TABLE_NAME", Properties.Settings.Default.DBSchema);
        HasKey(s => s.Id);

        Property(s => s.Id).HasColumnName("COLUMNNAME");
    }
}

EDIT 2 :

_dbContext is a custom object built following EF 5 Repository and Unit of Work Patterns :

https://learn.microsoft.com/fr-fr/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Like so :

public class UserManager : IDisposable
{        
    private readonly IRepository _dbContext;
}

public interface IRepository
{
    TEntity Update<TEntity>(TEntity entity) where TEntity : class;
}

EDIT 3 :

The object actually gets its value emptied when going through the Attach function :

public TEntity Update<TEntity>(TEntity entity) where TEntity : class
    {
        try
        {
            TEntity attachedEntity = Set<TEntity>().Attach(entity);
            var entry = Entry(entity);
            entry.State = System.Data.EntityState.Modified;
        }
        catch(Exception e)
        {

        }
        return entity;
    }
like image 641
Steeven Diard Avatar asked Apr 10 '18 11:04

Steeven Diard


1 Answers

I don't know how is your mapping but you can use something like this

public class Example
{
    //ohter properties

    [Column("id_reference")
    public int IdReference { get; set; }

    [ForeignKey("IdReference ")]
    public virtual Reference ReferenceObj { get; set; }
}

in this example only the IdReference property is mapped and set ReferenceObj property is linked IdReference, using the virtual modifier you must to specify when you wants to load this property, to do this uses .Include("ReferenceObj") on your query (example dbContext.Examples.Where(x => x.Id > 0).Include("ReferenceObj"). This can works in your case, because only IdReference property is mapped

like image 185
Alexandre Heinen Avatar answered Oct 11 '22 18:10

Alexandre Heinen