Dear colleagues.
I'm developing a C#
Winform
application 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 in relation to database manipulation.
I'll put down parts of my system to see if they can help me make this code functional. To be more objective, my code until it was working but without the proper relationships between the tables. When I modified it so the tables had relationships it started giving errors, as this follows.
Thanks for the help.
System.Data.Entity.Infrastructure.DbUpdateException HResult = 0x80131501 Message = Entities in 'BancoContexto.PedidoCtx' participate in the 'Client_PedidoPrincipalX' relationship. 0 related 'Client_PedidPrincipalX_Source' were found. 1 'Client_PedidPrincipalX_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);
}
}
}
Excerpt of code 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();
}