6
How to add properties (columns) in an N-N relation using EF?
For example, I have the class Produto
:
public class Produto
{
[Key]
public int ProdutoID { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public virtual ICollection<Venda> Vendas { get; set; }
public Produto()
{
this.Vendas = new List<Venda>();
}
}
And I got the class Venda
:
public class Venda
{
[Key]
public int VendaID { get; set; }
public string Descricao { get; set; }
public decimal Total { get; set; }
public virtual ICollection<Produto> Produtos { get; set; }
public Venda()
{
this.Produtos = new List<Produto>();
}
}
I’m using Code First and therefore EF automatically creates a table VendaProdutos
, the problem is that this table should have more fields, as Quantidade
, etc..
Is there any way I can do this without running away from Code First or will have to look for another way to map my classes (Fluent API for example)?
You will have to create a new class that will stay between your relationship in order to have a new property.
– Filipe Oliveira
Then I would have to switch these N-N relations to 1-N relations right. I hadn’t thought about it.
– Jéf Bueno
Exactly, in case it would have a class
ProdutoVenda
in the middle.– Filipe Oliveira
Relations
NxM
are made in order to have an intermediate table that receives a relation1xN
of each of the other tables involved. In this specific case, the intermediate table (ProdutoVenda
) must have a key composed by the key pair of the two external tables. And once this intermediary is to receive an entry, one must make sure that the quantity sold does not exceed the stock...– mutlei