0

How do I map a navigation property when there is no key of its parent in it?

I mean

There is a class Contract. This is a contract of sale of a product and needs a product to exists. TB_Contract contains ProductId. The Product exists without a contract and there isn't a ContractId on TB_product.

In some cases the product can be in more than one contract, that's why it has been modeled as a many to one in bd. But in our classes it must be one-to-one

public class Contract
{
   ...
   public Product Product { get; set; }
   ...
}

public class Product
{
    ...
    public Contract Contract { get; set; }
    ...
}

table tb_Contract
(
   idContract,
   idProduct
)

table tb_Product
(
   idProduct,
   description,
)

I want my class Product have the contract which it's linked to, if there is one.

I'm using code first. How to I map it on EF6?

Dummy
  • 21
  • 7

1 Answers1

0

There's no way to map this as a one-to-one association. It's a one-to-many association by design. So if anything, the design should change to make it one-to-one.

Entity Framework models one-to-one associations by a foreign key that's also a primary key. Any other way to have one-to-one associations is by enforcing them through business logic.

In code, this means that Product has a collection of Orders and a validation rule that checks the number of items in this collection.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291