c# – How is the query generated in Linq assembled when we UPDATE?

Question:

How is the query generated in Linq assembled when we UPDATE?

using ColWebDBContext.DBase.Banco;
using System;
using System.Web.UI;
using System.Linq;

namespace DBContext
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (var ctx = new dbContext())
            {
                var Produto = ctx.Tabela_Produtos.FirstOrDefault(p => p.Produto == 1);
                Produto.Nome = "Bombril";
                ctx.SaveChanges();
            }
        }
    }
}

In the example above, I search for all the columns of the object (Table_Products), change the Name field and send the Context save, if I were doing the update query with the sql syntax it would be like this;

update Tabela_Produtos
set Nome = 'Bombril'
where Produto = 1;

My doubts are;

  1. Does the Context have any way to generate the same syntax?
  2. Is there any way to see the query that is being sent to the bank in this case?

The question below is the most critical and the one I'm most interested in knowing.

  1. How is it done by Context so that it knows that only the Name column has changed?

Answer:

  1. Does the Context have any way to generate the same syntax?

I don't know, but I don't think so… it makes no sense to use entity when you want to do ADO.NET "things".

  1. Is there any way to see the query that is being sent to the bank in this case?

Yes. You can create your own logger or create a simple extension:

public static class QueryHelper
{
    public static string TraceSql<T>(this IQueryable<T> t)
    {
        var sql = "";
        ObjectQuery<T> oqt = t as ObjectQuery<T>;

        if (oqt != null)
            sql = oqt.ToTraceString();

        return sql;
    }
}

Or:

ctx.Database.Log = x => System.Diagnostics.Debug.WriteLine(x);
  1. How is it done by Context so that it knows that only the Name column has changed?

Via GetModifiedMembers or via a small implementation:

using (var ctx = new dbContext())
{
    var Produto = (from p in ctx.Produto
                            where p.Produto == 1
                            select p).FirstOrDefault();
    Produto.Nome = "Bombril";

    QueryHelper<Product>.Log(db, Produto);//seu logger

    ctx.SaveChanges();
}


public static class QueryHelper
{
    public static void Log<T>(DataContext dataContext, T entidade) where T : Class
    {
        foreach(var propriedadeModificada in dataContext.GetTable<T>().GetModifiedMembers(entidade))
        {
            var valorAtual = propriedadeModificada.CurrentValue;
            var valorOriginal = propriedadeModificada.OriginalValue;
        }
    }
}
Scroll to Top