0
I am trying to create a Onetomany relationship between 2 classes "User and Broker" where 1 User has many Brokers. The problem is when I add a new Broker a new User is created and I don’t know why it happens
How to solve this?
User
public class Usuario
{
public long id { get; set; }
public String nome { get; set; }
public IList<Corretora> corretoras { get; set; }
}
Broker
public class Corretora
{
public long id { get; set; }
public String nome { get; set; }
public Usuario usuario { get; set; }
}
User
public class UsuarioMap : EntityTypeConfiguration<Usuario>
{
public UsuarioMap()
{
this.ToTable("Usuarios");
this.HasKey<long>(u => u.id);
this.Property(u => u.id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(u => u.nome).IsRequired().HasMaxLength(50);
//um usuario tem muitas corretoras
HasMany(u => u.corretoras).WithRequired(c => c.usuario);
}
}
Brokeramap
public class CorretoraMap : EntityTypeConfiguration<Corretora>
{
public CorretoraMap()
{
this.ToTable("Corretoras");
this.HasKey<long>(c => c.id);
this.Property(c => c.id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(c => c.nome).IsRequired().HasMaxLength(50);
HasRequired(u => u.usuario).WithMany(c => c.corretoras);
}
}
It wasn’t clear to me what you mean by "when I add a new Broker"... but try the following: comment the line
HasRequired(u => u.usuario).WithMany(c => c.corretoras);
of Brokeramap and retained.– Renan
If possible put the excerpt in which is filling the entity "Broker" before inserting in the BD.
– George Wurthmann
Cade the insertion code, which demonstrates the creation of the user?
– novic