Relationship 1x1(or not)

Asked

Viewed 82 times

1

I have 2 entities:

Itempedido and Product...

Using the Fluent API as I say to my Itempedido entity that she has a Product?

Note: The product entity cannot have dependencies, although 1 product can be in several itemPedido I do not want it to depend on an itemPedido to exist...

Product class:

namespace DTO
{
    public class ProdutoDTO
    {
        public int produtoID { get; set; }
        public int codigo { get; set; }
        public string descricao { get; set; }
        public decimal preco { get; set; }
    }
}

Itempedido class:

namespace DTO
{
    public class ItemPedidoDTO
    {
        public int itemPedidoID { get; set; }
        public int quantidade { get; set; }
        public int porcentagemDesconto { get; set; }

        public int produdoID { get; set; }
        public virtual ProdutoDTO produto { get; set; }
    }
}
  • And where is the code?

  • I edited and put them.

  • 1

    Okay, I don’t see any dependency on ProdutoDTO with ItemPedidoDTO, what is your doubt? There is no third "entity" PedidoDTO, which will store the ItemPedidoDTO? Ps.: the attribute preco should stay in the ItemPedidoDTO, otherwise if you change the price of a product, will change the value in all your orders already made.

  • Yes there is the entity Pedidodto, I who removed from the code the request and virtual request thinking that I did not need to show since I did not talk about it... our well observed, nor noticed the question of price, vlw! My question is: "what I write with Fluent API in the class-specific Entity Framework configuration to say that Itempedido has a Product, but the Product has no dependency?"

1 answer

2


You can use the following code to map the unidirectional relationship:

modelBuilder.Entity<ItemPedidoDTO>().HasRequired(i => i.produto).WithMany();
  • Hasrequired configures the relationship for product as mandatory
  • Withmany() sets the relationship to be mandatory:many without navigation property on the many side

If English is easy for you, consider reading this link https://stackoverflow.com/a/20909649/2721661

Browser other questions tagged

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