Excluding properties from update instead of updating whole object

asp.net-mvc-5 aspnetboilerplate c# change-tracking entity-framework-6

Question

I am using ASP.NET Boilerplate with Code-First Entity Framework 6 and MVC 5.

In order to update an entity, I am using UpdateAsync.

How can I exclude some properties from the entity before executing update?

What function should I use and is this implemented in ASP.NET Boilerplate or not yet?

I have achieved that in Entity Framework 6 as follows:

public virtual TEntity UpdateWithExcludeProperities(TEntity entity,string [] properities)
{
    if (entity == null)
        throw new ArgumentException("Paramter cannot be null", "entity");

    var existedEntity = SelectFromContext(entity.ID);
    if (existedEntity == null)
        throw new ObjectNotFoundException("Record is not found!");

    _context.Entry(existedEntity).CurrentValues.SetValues(entity);
    foreach (var name in properities)
    {
        _context.Entry(existedEntity).Property(name).IsModified = false;
    }
    _context.SaveChanges();
    return existedEntity;
}

public virtual TEntity SelectFromContext(Guid id)
{
    TEntity entity;
    entity = DbSet<TEntity>().SingleOrDefault(e => e.ID == id);
    return entity;
}

But is there any possibility to implement this code in ASP.NET Boilerplate?

1
0
4/13/2019 1:11:41 AM

Accepted Answer

i was able to do that in ASP.NET Boilerplate as following by working with Ef core LINQ queries directly only

public virtual TEntity SelectFromContext(TPrimaryKey id)
{
    TEntity entity;
    entity = Repository.GetDbContext().Set<TEntity>().SingleOrDefault(e => e.Id.Equals(id));
    return entity;
}

public virtual async Task<TEntity> UpdateWithExclude(TEntity entity, string[] properities)
{
        if (entity == null)
            throw new ArgumentException("Paramter cannot be null", "entity");

        var existedEntity = SelectFromContext(entity.Id);
        if (existedEntity == null)
            throw new ObjectNotFoundException("Record is not found!");

        var currentValues = Repository.GetDbContext().Entry(existedEntity).CurrentValues;

        foreach (var properteyName in currentValues.PropertyNames)//make default false value for all 
        {
            var y = Repository.GetDbContext().Entry(existedEntity).Property(properteyName);
            if (!properities.Contains(y.Name))
                Repository.GetDbContext().Entry(existedEntity).Property(properteyName).IsModified = false;
        }

        Repository.GetDbContext().Entry(existedEntity).CurrentValues.SetValues(entity);

        Repository.GetDbContext().SaveChanges();
        var UpdatedEntity = SelectFromContext(entity.Id);
        return await Task.FromResult(UpdatedEntity);
}
0
4/15/2019 12:36:24 PM

Popular Answer

you are on the wrong path! it's very simple to update an entity with the specified fields.

1- Create a DTO.

2- Configure mapping

3- Get entity and map DTO to entity.

Checkout my example. In this example Student entity has 3 properties. In the StudentAppService UpdateOnlyNameOfStudent() method, we update only Name field of Student. And notice that I even didn't run _studentRepository.Update(student) because AspNet Boilerplate commits the changes when the method ends (See automatic save change)

StudentDto.cs

[AutoMapFrom(typeof(Student))]
public class StudentDto: EntityDto<long>
{
     public string Name { get; set; }    
}

Student.cs

public class Student: Entity
{
     public string Name { get; set; }  

     public int SchoolNumber { get; set; }  

     public DateTime RegisterDate { get; set; }  
}

StudentAppService.cs

public class StudentAppService : IStudentAppService 
{
    private readonly IRepository<Student> _studentRepository;


    public RoleAppService(IRepository<Student> studentRepository)
    {
       _studentRepository = studentRepository;
    }

    public override async void UpdateOnlyNameOfStudent(StudentDto input)
    {
        var student = _studentRepository.Get(input.Id);
        ObjectMapper.Map(input, student);
    }

    /*
    public override async void UpdateOnlyNameOfStudent_Alternative(StudentDto input)
    {
        var student = _studentRepository.Get(input.Id);
        student.Name = input.Name;            
    }
    */
}

AspNet Boilerplate uses AutoMapper to map objects. See Object To Object Mapping



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow