Input Entityframework C#

Asked

Viewed 103 times

1

I have 3 Entity, where are Countries, States and Cities. I am performing the Crud of the City Entity, and saving is asking for the relationship of States and Countries, but this I do not need, because I have a property called Estadohandle in the City Entity to perform the Insert, for example:

The error that occurs is that says that the Entity parents does not exist, because state relates to parents, and city relates to state, in this case when entering has how to take this relationship not to ask the filling of the Entity Parents in the state that I am selecting in the Entity city ?

Entity Cidade

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

Mapping of the Entity

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 that calls the method 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);
        }            
    }

1 answer

0

Nicola Bogar Stop Adding Unnecessary Complexity to Your Code.

the class Entity<T> and extensions as Insert(this EntityBase entity) only bring you trouble.

In your specific case, Entity<Estados> for being a static class, you do not have access to your _context, then it should create a new context to be able to carry out the consultation, in this way the _context is not tracking the estado.

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

as regards the Insert(this EntityBase entity), this code in nothing adds, just use the 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, then it is not a good add to your own implementation of Repository on top of the EF

  • @NicolaBogar https://answall.com/q/51536/2363

Browser other questions tagged

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