How do I search and save a single field?

6

How can I fetch a single field from the table change it and save this field without having to fetch all fields from the table?

The reason for this is simple, I have some tables that have more than 30 columns and this has a high cost of processing in the application when the times are updated only one field of this table, as in the example below, I have the Cities table and I just need to change the name of the city, how could I search and change only the Name field?

Obs ; I am using system.data.linq.datacontext my context is like this.

public System.Data.Linq.Table<Tabela_ScanImagen> Tabela_ScanImagens
{
    get
    {
        return this.GetTable<Tabela_ScanImagen>();
    }
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Tabela_ScanImagens")]
public partial class Tabela_ScanImagen : INotifyPropertyChanging, INotifyPropertyChanged
{   
    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);  
    private double _Imagem; 
    private string _Path;   
    private System.Nullable<double> _Cliente;   
    private System.Nullable<double> _Orcamento; 
    private System.Nullable<double> _Documento; 
    private System.Nullable<double> _Alteracao; 
    private System.Nullable<double> _Sinistro;  
    private System.Nullable<double> _Seguradora;    
    private System.Nullable<double> _Divisao;   
    private string _Descricao;
}

I tried to do it using the EntityFramework.Extended package, but it only accepts the context being System.Data.Entity DbContext

public void Salvar()
    {
        using (var dm = new DmContext())
        {
            var _descricao = dm.Tabela_ScanImagens
                 .Where(c => c.Imagem == 6)
                 .Select(c => c.Descricao)
                 .FirstOrDefault();

            dm.Tabela_ScanImagens.Update(c => new Tabela_ScanImagen { Descricao = "teste" });

            dm.SaveChanges();
        }
    }

That way it returns me the following error.

  

The query must be of type ObjectQuery or DbQuery. Parameter name:   source

    
asked by anonymous 22.10.2016 / 23:35

3 answers

5

There are a few ways to do this:

1. Using the EntityFramework.Extended package

Install the package

  

PM > Install-Package EntityFramework.Extended

Then you can do the following

using EntityFramework.Extensions;

public void Salvar()
{
    using (var ctx = new ExemplosEntities())
    {
        ctx.Cidades.Where(c => c.IdCidade == 1)
                   .Update(c => new Cidade { Nome = "São Carlos" });

        ctx.SaveChanges();
    }
}

2. Using ExecuteCommand()

using (var ctx = new ExemplosEntities()) 
{ 
    var command = "UPDATE dbo.ScanImagens SET Descricao = 'Teste' WHERE Id = 1";
    context.Database.ExecuteSqlCommand(command); 
}

More examples here

3. Using the IsModified

You can also "warn" the context that not all properties have been modified in this way.

using (var dm = new DmContext())
{
    var excluded = new [] { "Id", "Nome", "Etc" };
    // array com as propriedades não modificadas

    var entry = dm.Entry(obj);
    foreach (var name in entry.CurrentValues.PropertyNames.Except(excluded))
    {
        entry.Property(name).IsModified = true;
    }           

    dm.SaveChanges();
}
    
23.10.2016 / 00:27
0
  public void Salvar()
   {
     using (var ctx = new ExemplosEntities())
       {

          var Cidade = ctx.Cidade.First(c => c.IdCidade == 1);

          Cidade.Nome = "São Carlos";

          ctx.SaveChanges();
       }
    }

check on this:

var Cidade = ctx.Cidade.First(c => c.IdCidade == 1);

    
23.10.2016 / 00:47
0

I honestly prefer the answer from @jbueno, which uses EntityFramework.Extended .

But since you use system.data.linq.datacontext , I do not know if it applies. As I mentioned in the comments, you can use a procedure or execute a sql command through DbContext. That way you do not need to make any extra query to db to change the required columns.

It is necessary to validate the strings that will be concatenated to the SQL command, to avoid injections of code like SQL Injection.

Ex.

public int AlterarDescricao(string novaDescricao)
{
    int linhasAfetadas = 0;
    //Crie um método para validar a string novaDescricao contra possível injeções de código.
    var stringValidadaContraSqlInjection = ValidarInput(novaDescricao);
    using (var dm = new DmContext())
    {
        linhasAfetadas = dm.ExecuteCommand("UPDATE Tabela_ScanImagen SET Descricao = {0} WHERE Imagem  = 6", stringValidadaContraSqlInjection );
    }
    return linhasAfetadas;
}

Reference: link

    
26.10.2016 / 17:24