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);
}
}
@NicolaBogar https://answall.com/q/51536/2363
– Tobias Mesquita