Why does the one-to-many relationship in the Entity Framework by default not work?

Asked

Viewed 57 times

0

[Table(name: "cliente", Schema = "estudo")]
public class Cliente : Base
{
    [Key, Column("COD_CLIENTE")]
    [Required]
    public override Int64 Id { get; set; }

    [Column("CLI_NOME")]
    [Required]
    public virtual String Nome { get; set; }

    [Column("CLI_EMAIL")]
    [Required]
    public virtual String Email { get; set; }

    [Column("CLI_ENDERECO")]
    [Required]
    public virtual String Endereco { get; set; }

    [Column("CLI_BAIRRO")]
    [Required]
    public virtual String Bairro { get; set; }

    [Column("CLI_CIDADE")]
    [Required]
    public virtual String Cidade { get; set; }

    [Column("CLI_ESTADO")]
    [Required]
    public virtual String Uf { get; set; }

    ICollection<Produto> Produtos { get; set; }
}                                               

[Table(name: "produtos", Schema = "estudo")]
public class Produto : Base
{
    [Key, Column("COD_Produto")]
    [Required]
    public override Int64 Id { get; set; }

    [Column("NOME")]
    [Required]
    public virtual String Nome { get; set; }

    [Key, Column("COD_CLIENTE")]
    [Required, ForeignKey("Cliente")]
    public virtual Int64 ClienteId { get; set; }

    public Cliente Cliente { get; set; }
}

My context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    var typesToMapping = (from x in Assembly.GetExecutingAssembly().GetTypes()
                          where x.IsClass && typeof(IMapping).IsAssignableFrom(x)
                          select x).ToList();

    foreach (var mapping in typesToMapping)
    {
        dynamic mappingClass = Activator.CreateInstance(mapping);
        modelBuilder.Configurations.Add(mappingClass);
    }
}

Now, how do I make the relationships between the tables a one-to-many standard?

1 answer

0

I believe the problem is the level of protection of the object products, is private, but by convention add also the virtual in the objects referenced:

In the client class make Collection public virtual:

public virtual ICollection<Produto> Produtos { get; set; }

In the Product class make the Customer virtual:

public virtual Cliente Cliente { get; set; }

That should solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.