0

I'm using EF Code first and want to create such structure for example:

  1. There is "Invoice" model
  2. And also we have other entities like Client, Customer, etc that may have a list of Invoices

basically the relation is one to many. One invoice can belong only to a Client, or a Customer, etc

I want to store all invoices in the same table since is the same model for all, and using fluent api want to create the relation tables

something like this below is for many to many:

modelBuilder.Entity<Client>()
             .HasMany(c => c.Invoice).WithMany(i => Clients)
             .Map(t => t.MapLeftKey("ClientID")
                 .MapRightKey("InvoiceID")
                 .ToTable("ClientInvoices"));

modelBuilder.Entity<Customer>()
             .HasMany(c => c.Invoice).WithMany(i => Customer)
             .Map(t => t.MapLeftKey("CustomerID")
                 .MapRightKey("InvoiceID")
                 .ToTable("CustomerInvoices"));

How can i do that for one to many ? How to have 2 tables where to store the ClientInvoices , CustomerInvoices ?

Corina
  • 1

1 Answers1

0

Declare both classes with navigation properties to each other. Mark one of the tables (the dependent table) with the ForeignKey attribute on its Primary Key. EF infers one-to-meny from this:

public class Customer
{
    public int Id { get; set; }
    ...
    public List<Invoice> Invoices{ get; set; }
    ...
}
public class Invoice
{
   public int Id { get; set; }

   ...
   [ForeignKey("Customer")]
   public int CustomerId { get; set; }

   public Customer Customer { get; set; }
}
Hossein
  • 3,083
  • 3
  • 16
  • 33
  • Yes but in this case in the Invoice table i will have CustomerId column, then ClientId, and maybe some other if invoice will be used for some other. – Corina Jul 27 '18 at 11:51