简体   繁体   中英

Entity Framework Code First: multiple one to many

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 ?

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM