2
Hello.
I have the following classes...
Sales class:
[Table("venda")]
public class Vendas
{
public Vendas()
{
ItensVendas= new List<ItensVendas>();
}
[Key]
public int Id { get; set; }
public string NOME_VENDA { get; set; }
public DateTime? DATA { get; set; }
public int ID_CLIENTE { get; set; }
public virtual IEnumerable<ItensVendas> ItensVendas{ get; set; }
}
Itenssales class:
[Table("ITENS_VENDA")]
public class ItensVendas
{
[Key]
public int Id { get; set; }
public int ID_RPODUTO { get; set; }
public int QTD { get; set; }
public decimal VALOR { get; set; }
[ForeignKey("venda")]
public int VendaId { get; set; }
public virtual Vendas venda { get; set; }
}
Controller:
public class VendasController : ApiController
{
private Contexto ctx = new Contexto();
[HttpGet]
public IEnumerable<Vendas> GetVendas()
{
using (Contexto vendaCtx = new Contexto()) {
return vendaCtx.Vendas.ToList();
}
}
}
Context:
public class Contexto : DbContext
{
public Contexto() : base("conn")
{
this.Configuration.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
public DbSet<Vendas> Vendas { get; set; }
public DbSet<ItensVendas> ItensVendas { get; set; }
}
In the Getsales controller method, Eleme returns a JSON containing the sale data, but the sale items come empty as below.
[{"Id":1,"NOME_VENDA":"VENDA 1","DATA":"2017-11-15T20:08:52","ID_CLIENTE":1,"ITENSVENDAS":[]}]
I’d like to bring the items from this sale too, how could I do that?
Thank you!
I enabled Lazy loading, but started having the following error: The Entitytype Models.Sales does not declare a navigation Property with the name 'Itenssales'. And in class I have a Property with this name.
– Core
Beauty, but in your Configuration (where you map your entities to generate the bank), there is this relationship?
– Ayrton Giffoni
switch to public virtual Ienumerable<Itenssales> Itensvendas{ get; set; } (put the VIRTUAL) and test again, if it is mapped all right to generate the bank.
– Ayrton Giffoni
Even switching to public virtual Ienumerable<Itenssales> Itenssales{ get; set; } the error remains the same.
– Core
Then post (edit your question) how you configured the mapping of your classes for me to check if there are any errors?
– Ayrton Giffoni
@Core changed to Icollection tb, because when it comes from the bank, it understands as a collection
– Ayrton Giffoni
Same mistake. You talked about the mapping, would have to have a new class for that? I did the example of a video lesson , was done on top of an existing base.
– Core
you ta mapping with date Annotation?
– Ayrton Giffoni
Yes. The correct thing would be to use Fluent api?
– Core
I believe it is the best scenario. You will hardly have problems of this type configuring with the Fluent. If you need help with the mapping, you can find me.
– Ayrton Giffoni