简体   繁体   中英

How to join list of ids with another table many to many in EFcore3.1?

Hi everyone i have many to many relation between invoice and product and the join class is customer invoice i want to insert invoice and add many product to it. one of the answer when i ask in other place told me you make list of product while your join class take only one product but if you make it list of product inside the customer invoice it will work and i make it still not work anyone can explain and how the code should be this is the function.

 try
            {

                Invoice invoice = new Invoice
                {
                    InvoiceNote = addCustomerInvoice.InvoiceNote,
                    AdminId = addCustomerInvoice.AdminId,
                    CustomerId = addCustomerInvoice.CustomerId,
                    CompanyStoresId = addCustomerInvoice.CompanyStoresId,
                    InvoiceDate = addCustomerInvoice.InvoiceDate.Date,
                    
                };
                
                List<int>result= await _drugDbContext.Products.Select(p => p.ProductId).ToListAsync();
                


                CustomerInvoice customerInvoice = new CustomerInvoice
                {
                    Products =result,
                    Invoice = invoice
                    
                };
                await _drugDbContext.CustomerInvoices.AddAsync(customerInvoice);
                await _drugDbContext.SaveChangesAsync();
                servicesResponse.Data = _mapper.Map<InvoiceForGet>(invoice);
            }
public class Invoice
    {
        public int InvoiceId { get; set; }
        public DateTimeOffset InvoiceDate { get; set; } = DateTimeOffset.UtcNow;
        public string InvoiceNote { get; set; }
        public int CustomerId { get; set; }
        public Customer Customer { get; set; }
        public int AdminId { get; set; }
        public Admin Admin { get; set; }
        public int CompanyStoresId { get; set; }
        public CompanyStore CompanyStores { get; set; }
        public ICollection<CustomerInvoice> CustomerInvoices { get; set; }
         = new List<CustomerInvoice>();
        public ICollection<ProductsReturn> ProductsReturn { get; set; }
         = new List<ProductsReturn>();
    }
public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string Company { get; set; }
        public float Price { get; set; }
        public int Quantity { get; set; }
        public string Description { get; set; }
        public string ProductImage { get; set; }
        public string BarCode { get; set; }
        public float BuyPrice { get; set; }
        public ICollection<ProductAndCategory> ProductCategory { get; set; }
= new List<ProductAndCategory>();
        public ICollection<TransportInvoice> transportInvoices { get; set; }
= new List<TransportInvoice>();
        public ICollection<CustomerInvoice> CustomerInvoices { get; set; }
       = new List<CustomerInvoice>();
        public ICollection<ProductsReturn> ProductsReturn { get; set; }
      = new List<ProductsReturn>();
        public int CompanyStoresId { get; set; }
        public CompanyStore CompanyStores { get; set; }
        public ICollection<OfficeInvoice> OfficeInvoices { get; set; }
   = new List<OfficeInvoice>();
        public ICollection<OfficeReturn> OfficeReturns { get; set; }
    = new List<OfficeReturn>();
    }
modelBuilder.Entity<CustomerInvoice>(entity =>
            {
                modelBuilder.Entity<CustomerInvoice>().HasKey(ci => new { ci.ProductId, ci.InvoiceId });
                entity.HasKey(c => c.CustomerInvoiceId);
                entity.Property(c => c.Quantity).IsRequired();
                entity.Property(c => c.TotalPrice).IsRequired();
            });
            modelBuilder.Entity<CustomerInvoice>(entity =>
            {
                entity.HasOne(c => c.Products)
                       .WithMany(p => p.CustomerInvoices)
                       .HasForeignKey(c => c.ProductId)
                       .IsRequired(false)
                       .OnDelete(DeleteBehavior.NoAction);
            });
            modelBuilder.Entity<CustomerInvoice>(entity =>
            {
                entity.HasOne(c => c.Invoice)
                       .WithMany(i => i.CustomerInvoices)
                       .HasForeignKey(c => c.InvoiceId)
                       .IsRequired(false)
                       .OnDelete(DeleteBehavior.NoAction);
            });
public class CustomerInvoice
    {
        public int CustomerInvoiceId { get; set; }
        public int Quantity { get; set; }
        public float Discount { get; set; }
        public float TotalPrice { get; set; }
        public int InvoiceId { get; set; }
        public Invoice Invoice { get; set; }
        public int ProductId { get; set; }
        public Product Products { get; set; }
        public ICollection<ProductsReturn> ProductsReturn { get; set; }
       = new List<ProductsReturn>();
    }
this is the dto class
        public class AddCustomerInvoice
    {
        public ICollection<Product> products { get; set; }
         = new List<Product>();
        public DateTime InvoiceDate { get; set; }
        public string InvoiceNote { get; set; }
        public int CustomerId { get; set; }
        public int AdminId { get; set; }
        public int CompanyStoresId { get; set; }
    }

I made a simple demo based on your codes and requirement for how to insert a record with many-to-many relationship.

Below is the code:

Model:

public class Invoice
{
    public int InvoiceId { get; set; }
    public string InvoiceNote { get; set; }
    public ICollection<CustomerInvoice> CustomerInvoices { get; set; }
     = new List<CustomerInvoice>();
}

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public float Price { get; set; }
    public ICollection<CustomerInvoice> CustomerInvoices { get; set; }
   = new List<CustomerInvoice>();
}

public class CustomerInvoice
{
    public int CustomerInvoiceId { get; set; }
    public int Quantity { get; set; }
    public float TotalPrice { get; set; }
    public int InvoiceId { get; set; }
    public Invoice Invoice { get; set; }
    public int ProductId { get; set; }
    public Product Products { get; set; }
}

public class AddCustomerInvoice
{
    public ICollection<Product> products { get; set; }
     = new List<Product>();
    public string InvoiceNote { get; set; }
}

Controller:

public IActionResult Index()
{
    AddCustomerInvoice addCustomerInvoice = new AddCustomerInvoice
    {
        products = new List<Product> 
        { 
            new Product { ProductId = 1, Price = 3, Quantity = 10},
            new Product { ProductId = 2, Price = 5, Quantity = 10},
            new Product { ProductId = 3, Price = 6, Quantity = 10},
            new Product { ProductId = 4, Price = 2, Quantity = 10},
        },

        InvoiceNote = "ddddd"
    };

    Invoice invoice = new Invoice
    {
        InvoiceNote = addCustomerInvoice.InvoiceNote,
    };

    _drugDbContext.Invoices.Add(invoice);
    _drugDbContext.SaveChanges();

    int invoiceId = invoice.InvoiceId;

    foreach (var item in addCustomerInvoice.products)
    {
        _drugDbContext.CustomerInvoices.Add(
        new CustomerInvoice 
        { 
            InvoiceId = invoiceId, 
            ProductId = item.ProductId,
            Quantity = item.Quantity,
            TotalPrice = item.Quantity * item.Price
        });
        _drugDbContext.SaveChanges();
    }

    return View();
}

Result:

在此处输入图片说明

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