How to search and save a single field?

Asked

Viewed 269 times

6

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

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

Obs; I’m using system.data.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 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. Name of parameter: source

  • Then you can use the db.Executecommand() method to update only one field. (https://msdn.microsoft.com/pt-br/library/system.data.linq.datacontext.executecommand(v=vs.110). aspx)

  • 1

    Friend, this is one of the losses we have with Orms. Not all implement partial updates, or partial recovery of server data, as this would hinder the "transparency" with which one wants to deal with mapped objects. However, is this really harming your system’s performance, or are you trying to optimize before you instrumentalize a performance test using a specific application Profiling tool? If a bottleneck really appears, make direct calls to the DBMS, and you can even embed the UPDATE with SELECT in a single call. Don’t get stuck

  • I’m accepting the answer below, but she didn’t answer what she really wanted.

3 answers

5


There are some ways to do this:

1. Using the package Entityframework.Extended.

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 property IsModified

It is also possible to "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();
}

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

0

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

But how you use system.data.linq.datacontext I don’t know if it applies. As I mentioned in the comments, you can use a precedent or run a sql command through Dbcontext. This way you don’t need to perform 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 code injections 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: https://msdn.microsoft.com/pt-br/library/system.data.linq.datacontext.executecommand(v=vs.110). aspx

  • It’s not my goal to use that kind of command.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.