1
Dear colleagues.
I’m developing an application C#
Winform
with database SqlServer
and Entity framework
.
As I am inexperienced, I have been learning through the Internet.
I’m having a hard time understanding and implementing some concepts regarding object orientation regarding database manipulation.
I’ll put down the parts of my system to see if they can help me make this code work. To be more objective, my code until it was working but without the proper relationships between the tables. When I modified it so that the tables had relationships began to give errors, as this following.
I appreciate the help.
System.Data.Entity.Infrastructure.Dbupdateexception Hresult=0x80131501 Message=Entities in 'Bancocontexto.Pedidoctx' participate in the 'Cliente_pedidoprincipalx' Relationship. 0 Related 'Cliente_pedidoprincipalx_source' Were found. 1 'Cliente_pedidoprincipalx_source' is expected.
namespace DAL.MODEL
{
public class Cliente
{
public Cliente()
{
this.PedidoPrincipalX = new List<PedidoPrincipal>();
}
public int ClienteId { get; set; }
public string Nome { get; set; }
public virtual ICollection<PedidoPrincipal> PedidoPrincipalX { get; set; }
}
}
namespace DAL.MODEL
{
public class PedidoPrincipal
{
public int PedidoId { get; set; }
public DateTime DataEmissao { get; set; }
public Decimal Total { get; set; }
public int FK_ClienteId { get; set; }
public virtual Cliente ClienteX { get; set; }
}
}
namespace DAL.MAPPING
{
public class ClienteMap : EntityTypeConfiguration<Cliente>
{
public ClienteMap()
{
ToTable("Cliente");
HasKey(c => c.ClienteId);
Property(c => c.ClienteId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(X => X.PedidoPrincipalX);
}
}
}
namespace DAL.MAPPING
{
public class PedidoPrincipalMap : EntityTypeConfiguration<PedidoPrincipal>
{
public PedidoPrincipalMap()
{
ToTable("PedidoPrincipal");
HasKey(p => p.PedidoId);
Property(p => p.PedidoId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(X => X.ClienteX);
}
}
}
Code snippet to save to bank:
private void btnSalvar_Click(object sender, EventArgs e)
{
PedidoPrincipalRepositorio app = new PedidoPrincipalRepositorio();
PedidoPrincipal pedido = new PedidoPrincipal();
pedido.FK_ClienteId = Int32.Parse(txtCodigoCli.Text);
pedido.DataEmissao = DateTime.Now;
pedido.Total = decimal.Parse(txtValorTotal.Text);
app.Adicionar(pedido);
app.SalvarTodos();
}
Are you using Codefirst? If so, are you free to define field names and relationships? I say this because Codefirst has a very simple way of doing the relationship, which will help you even with CRUD
– Rodrigo K.B
Yes Rodrigo. I’m using Codefirst.
– Gilberto V. Gonçalves