Entity Framework 6 catch attributes in Savechanges

Asked

Viewed 68 times

0

I’m using the Entity Framework 6 with Oracle. The database is of a legacy system, I intend to set in hand the primary keys of the records.

To make life easier, I want to take SaveChanges of DbContext table data and fields that are primary key to execute the SQL command below, thus avoiding conflicts.

Doubt

In my DbContext, how do I get the attributes Table and Key and their respective values?

SQL

public int GetNextID(string field, string table)
{
    return Database.SqlQuery<int>("select coalesce(max(" + field + "), 0) + 1 from " + table).First();
}

Class

[Table("CHAMADOS")]
public class Chamado
{
    [Key]
    [Column("CD_CODIGO")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Codigo { get; set; }
    [Obrigatorio]
    [Column("CD_EM_CODIGO")]
    public int Empresa { get; set; }
}

My Dbcontext

public class OracleDbContext : DbContext
{
    public OracleDbContext()
        : base("OracleDbContext")
    {
        Database.SetInitializer<OracleDbContext>(null);
    }

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

    public override int SaveChanges()
    {
        foreach (var registro in ChangeTracker.Entries())
        {
            if (registro.State == EntityState.Added)
            {
                // Gostaria de pegar aqui os dados do atributo Table e Key da classe
            }
        }

        return base.SaveChanges();
    }

    public DbSet<Chamado> Chamado { get; set; }
}
  • There is no need for you to get your table id before saving, unless to do an update. of course if you use database IDENTITY.

  • First beware of this approach of selecting max, this would be a problem if Voce has a composite key and also you will be performing a reading on your table whenever you enter it, it is a dangerous approach. I also checked that Voce is using Oracle, have you tried using Quence with Trigger? It didn’t work as expected?

  • Following the @Nícolastarzia tip, with you use Oracle, why not use Sequence?

No answers

Browser other questions tagged

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