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

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 relationships between tables a one-to-many pattern?

    
asked by anonymous 14.10.2017 / 20:23

1 answer

0

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

In the client class, make the collection virtual public:

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

In the Product class make the Virtual Client:

public virtual Cliente Cliente { get; set; }

This should solve your problem.

    
15.10.2017 / 08:35