I have a small application in C #, WPF and EF6.
I'm using Code First , but I'm having a hard time creating a relationship. Look at my code, of the classes I want to relate: I am editing for the final version, if anyone has the same doubt.
public class Caixa
{
[Key]
public int CaixaId { get; set; }
public DateTime DataAbertura { get; set; }
public DateTime DataFechamento { get; set; }
public Boolean Aberto { get; set; }
public Decimal Troco { get; set; }
public Decimal TotalRetiradas { get; set; }
public Decimal TotalEntradas { get; set; }
public Decimal Total { get; set; }
public Decimal TotalEmCaixa { get; set; }
public String Observacoes { get; set; }
public Usuario Responsavel { get; set; }
public Caixa()
{
DataAbertura = DateTime.Now;
}
}
public class Usuario
{
[Key]
public int UsuarioId { get; set; }
[Required, Index(IsUnique=true)]
public String Login { get; set; }
[Required]
public String Password { get; set; }
public Boolean Administrador { get; set; }
}
public class Contexts: DbContext
{
//entidades
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Produto> Produtos { get; set; }
public DbSet<Caixa> Caixas { get; set; }
public Contexts()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Contexts>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
The code that saves is as follows:
database.Caixas.Add(NovoCaixa);
NovoCaixa.Responsavel = database.Usuarios.Single(u => u.UsuarioId == UsuarioAtivo.UsuarioId);
database.SaveChanges();
Whenever I try to save the Entity Box, I get this error:
System.Data.SqlServerCe.SqlCeException: A duplicate value cannot be inserted into a unique index. [ Table name = Usuario, Constraint name = IX_Login ]
I suspect that it is trying to insert the user, but it is not what I want, since it already exists.
Can anyone help me? I'm doing this project to learn EF.