从更新中排除属性,而不是更新整个对象

时间:2019-04-11 13:06:32

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

我正在将ASP.NET Boilerplate与Code-First Entity Framework 6和MVC 5一起使用。

为了更新实体,我使用UpdateAsync

如何在执行更新之前从实体中排除某些属性?

我应该使用什么功能?这是否已在ASP.NET Boilerplate中实现?

我已经在Entity Framework 6中实现了以下目标:

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;
}

但是有可能在ASP.NET Boilerplate中实现此代码吗?

2 个答案:

答案 0 :(得分:0)

您走错了路! 使用指定字段更新实体非常简单。

1-创建一个DTO。

2-配置映射

3-获取实体并将DTO映射到实体。

查看我的示例。在此示例中,Student实体具有3个属性。在StudentAppService UpdateOnlyNameOfStudent()方法中,我们仅更新Student的Name字段。并且请注意,我什至没有运行_studentRepository.Update(student),因为当方法结束时,AspNet Boilerplate会提交更改(请参见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使用AutoMapper映射对象。参见Object To Object Mapping

答案 1 :(得分:0)

仅通过直接使用Ef核心LINQ查询,我就可以在ASP.NET Boilerplate中实现以下目标

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);
}