Inserting data EntityFramework C #

1

I have 3 Entity, where are Countries, States and Cities. I am doing the Crud of entity City, and when saving it is asking the relationship of States and Countries, but this I do not need, as I have a property called StateHandle in the entity City to perform the insert, for example:

  The error that occurs is that it says that the entity parent does not exist, because state relates to parents, and city relates to state, in this case when inserting has to take this relationship to not request the completion of the entity Parents in the state that am I selecting in the entity city?

     

Entity City

public class Cidades : EntityBase
{
    public Cidades()
    {
        Estado = new Estados();
    }

    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public int EstadoHandle { get; set; }
    public Estados Estado { get; set; }       
}
  

Entity mapping

public class CidadesMapping : EntityTypeConfiguration<Cidades>
{
    public CidadesMapping ()
    {
        ToTable("CIDADES");

        HasKey(x => x.Handle);

        Property(x => x.Descricao)
            .HasMaxLength(150)
            .IsRequired();

        Property(x => x.Sigla)
            .HasMaxLength(3)
            .IsRequired();

        HasRequired(x => x.Estado)
            .WithMany(x => x.Cidades)
            .HasForeignKey(x => x.EstadoHandle);    
    }           
}
  

Creating a new city and performing the Insert method call below.

    private void Form1_Load(object sender, EventArgs e)
    {
        Estados estado = Entity<Estados>.GetByHandle(10);

        Cidades cidade = new Cidades();
        cidade.Handle = 50;
        cidade.Descricao = "CIDADE TESTE";
        cidade.Sigla = "TES";
        cidade.Estado = estado;
        cidade.EstadoHandle = estado.Handle;
        cidade.Insert();

    }   

    public static void Insert(this EntityBase entity)
    {
        try
        {
            DbSet dbSet = _context.Set(entity.GetType());
            dbSet.Add(entity);
            _context.Entry(entity).State = EntityState.Added;
            _context.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            string msng =  string.Empty;

            foreach (var error in e.EntityValidationErrors)
            {
                msng += "Entity: " + error.Entry.Entity.GetType().Name;
                msng += "\n";
                msng += "State: " + error.Entry.State;
                msng += "\n";

                foreach(var erro in error.ValidationErrors)
                {
                    msng += "Property: " + erro.PropertyName;
                    msng += "\n";
                    msng += "Erro: " + erro.ErrorMessage;
                }
            }
            throw new Exception(msng);
        }            
    }
    
asked by anonymous 26.06.2017 / 19:42

1 answer

0

Nicola Bogar stops adding unnecessary complexity to your code.

class Entity<T> and extensions as Insert(this EntityBase entity) will only cause problems.

In your specific case, Entity<Estados> because it is a static class, you do not have access to your _context , so you should create a new context to be able to query it, so _context is not crawling the estado .

If you use a Singleton pattern and its _context is global, then you will have even greater problems because EF is not designed to be used in this way.

As for Insert(this EntityBase entity) , this code does not add anything, just use DbSet<T>.AddAsync(T) .

using (var contexto = new MyContext())
{
    await var estado = contexto.Estados.FindAsync(10);
    var cidade = new Cidades();
    cidade.Handle = 50;
    cidade.Descricao = "CIDADE TESTE";
    cidade.Sigla = "TES";
    cidade.Estado = estado;
    cidade.EstadoHandle = estado.Handle;
    await contexto.Cidades.AddAsync();
    await contexto.SaveChangesAsync();
}

Finally, Entity Framework already implements Patterns as Unit of Work and Repository , so it's not a good add to your own implementation of Repository above EF

    
26.06.2017 / 20:22