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