Write include date using Entity framework

Asked

Viewed 773 times

5

I believe there was a misinterpretation, I’m posting the code to be better understood. I am using a project for my EF Repository is inside it I have:

Note the doubt in //companySalvar.DATA_IND = Datetime.Now; this is possible

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Projeto.Financeiro.Dominio;
using Projeto.Financeiro.Dominio.contrato;

namespace Projeto.Financeiro.RepositorioEF
{
    public class EmpresaRepositorioEF : IRepositorio<tb_empresa>
    {

        private readonly Contexto contexto;

        public EmpresaRepositorioEF()
        {
            contexto = new Contexto();
        }

        //salvar ou altera o registro
        public void SalvarRegistro(tb_empresa entidade)
        {
            if (entidade.IDEMPRESA > 0)
            {
                var empresaAlterar = contexto.Empresa.First(x => x.IDEMPRESA == entidade.IDEMPRESA);
                empresaAlterar.RAZAO_SOCIAL = entidade.RAZAO_SOCIAL;
                empresaAlterar.ENDERECO = entidade.ENDERECO;
                empresaAlterar.BAIRRO = entidade.BAIRRO;
                empresaAlterar.CIDADE = entidade.CIDADE;
                empresaAlterar.IMAGEM_LOGO = entidade.IMAGEM_LOGO;
                empresaAlterar.STATUS = entidade.STATUS;
                empresaAlterar.DATA_ALT = entidade.DATA_ALT;
            }
            else
            {
                //empresaSalvar.DATA_IND = DateTime.Now; isso é possivel
                contexto.Empresa.Add(entidade);
            }

            contexto.SaveChanges();
        }

        //excluir o registro
        public void ExcluirRegistro(tb_empresa entidade)
        {

            var empresaExcluir = contexto.Empresa.First(x => x.IDEMPRESA == entidade.IDEMPRESA);
            contexto.Set<tb_empresa>().Remove(empresaExcluir);
            contexto.SaveChanges();
        }

        //listar por id
        public tb_empresa ListarPorId(string id)
        {
            int idInt;
            Int32.TryParse(id, out idInt);
            return contexto.Empresa.First(x => x.IDEMPRESA == idInt);
        }

        //listar todos
        public IEnumerable<tb_empresa> ListarTodos()
        {
            return contexto.Empresa;
        }


    }
}

my Entity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Projeto.Financeiro.RepositorioEF
{
     public interface IEntidade
     {
          DateTime DATA_ALTERACAO { get; set; }
          DateTime DATA_INCLUSAO { get; set; }
     }
}

my Context:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Projeto.Financeiro.Dominio;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Validation;

namespace Projeto.Financeiro.RepositorioEF
{
    public class Contexto:DbContext
    {

        public  Contexto() : base("BancoDados")
        {

        }


        public override int SaveChanges()
        {
            var Contexto = ((IObjectContextAdapter)this).ObjectContext;

            IEnumerable<ObjectStateEntry> objectStateEntries =
            from e in Contexto.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
            where
                e.IsRelationship == false &&
                e.Entity != null &&
                typeof(IEntidade).IsAssignableFrom(e.Entity.GetType())
            select e;

            var dataAtual = DateTime.Now;

            foreach (var entry in objectStateEntries)
            {
                dynamic entityBase = entry.Entity;

                if (entry.State == EntityState.Added || entityBase.DataCriacao == DateTime.MinValue)
                {
                    entityBase.DATA_INCLUSAO = dataAtual;

                }

                entityBase.DATA_ALTERACAO = dataAtual;
            }

            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }


        public DbSet<tb_empresa> Banco { get; set; }





        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        }


    }
}
  • I made the code change, see if it was clearer.

  • Perfect. I just missed the DbSet<Empresa>. Where is it? Don’t forget to implement the interface IEntidade in Empresa.

  • I made the correction, is there the tb_company is the Ientidade with the correct fields, now how can I use these dates in my Empresarepositorioef? that’s all that’s left

  • If Empresa implements TEntidade and you set the two date fields. just test. No need to change the repository. You can put a breakpoint in SaveChanges, if you want to see how it works.

1 answer

6


The correct way is to put the date update on SaveChanges of context:

    public override int SaveChanges()
    {
        var context = ((IObjectContextAdapter)this).ObjectContext;

        IEnumerable<ObjectStateEntry> objectStateEntries =
            from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
            where
                e.IsRelationship == false &&
                e.Entity != null &&
                typeof(IEntidade).IsAssignableFrom(e.Entity.GetType())
            select e;

        var dataAtual = DateTime.Now;

        foreach (var entry in objectStateEntries)
        {
            dynamic entityBase = entry.Entity;

            if (entry.State == EntityState.Added || entityBase.DataCriacao == DateTime.MinValue)
            {
                entityBase.DataCriacao = dataAtual;

            }

            entityBase.UltimaModificacao = dataAtual;
        }

        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
    }

Reading the code, note that you will have to do your Models implement IEntidade, whose code is below:

public interface IEntidade
{
    DateTime UltimaModificacao { get; set; }
    DateTime DataCriacao { get; set; }
}

IEntidade forces his Models to have a creation date and one of the last modification. You don’t need to put anything in the Controller: the context does it all alone.

  • Hello Gypsy, it is evident that you have enough knowledge, but your answers are very difficult to be understood is taken advantage, when you say the "correct way " there are so many standards for development that this correct way may not be so correct.

  • Why? Explain to me your difficulty so I can make the answer more accessible.

  • I made the change of my question is all the code, where I could be adjusting my code according to what you’re answering?

  • Within the class Contexto. If Contexto is a DbContext, has a virtual method called SaveChanges. That is, my answer reimplementates this method. So, all Model implementing the interface IEntidade will be updated alone with the dates. You do not need to write code to update these dates on Controller. It became clearer?

  • I added my Context, could you check how I can do that? If I select the Dbcontext is to click F12 I will be redirected to the virtual method, are you referring to change this? att

  • No, no. Just paste the whole code into the class Contexto. Then also implement the interface IEntidade inside the directory Models of your system. Then do Empresa implement IEntidade, thus: public class Empresa: IEntidade.

  • Ok. I did what you said, I added the final code in my reply, this compiling, now how can I use in Empresarepositorioef? thank you

  • So you don’t need to change anything in the repository. Just change the Models and put in them the interface IEntidade and two more fields: public DateTime UltimaModificacao { get; set; } and public DateTime DataCriacao { get; set; }.

  • I wanted to add this to my Empresarepositorioef, so that everything is standardized

  • As I said, you don’t need it. If the repository doesn’t even need to set change or include dates. EF does it all by itself. By the way, you don’t even need to implement a repository because EF is already a repository.

  • To align ideas within an understanding that’s easier for me. &#xA;1 – Observe o meu EmpresaRepositorioEF : IRepositorio<tb_empresa>&#xA;2 – Ele tem um public void SalvarRegistro(tb_empresa entidade)&#xA;3 – na edição ele recebe os campos &#xA;4 – quero adicionar as Entidades para ficar no mesmo padrão

  • You don’t need any of this. You just need to implement IEntidade us Models where you want to save the dates. As the code is already in the SaveChanges (and every record of every entity goes through it to save), you do not need to put nothingness in the repository. Understood?

  • OK, it was not what I expected, but all right, since there is no other way, but it was a good learning.

Show 8 more comments

Browser other questions tagged

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