Get data of all entities in a many-to-many relationship

ⅰ亾dé卋堺 提交于 2019-12-02 12:09:12

问题


picture of DB My database has 3 tables Customers, Films and CustomersFilms is the brige table between Films and Customers now, I want to diaplay a table of cutomers with the movies they rented. I wrote a function that does the job for spesific id ( in the code 8 and 9 ). My Question is how to show the data to all entitys ?

   public ActionResult GetData()
    {
        MyDatabaseEntities2 db = new MyDatabaseEntities2();
        var q = (from c in db.Customers
                 from Films in db.Films
                     where Films.FilmId == 8
                     where c.CustomerId == 9
                 select new
                 {
                     c.CustomerName,
                     c.Phone,
                     c.FilmId,
                     c.CustomerId,
                      FilmName = Films.FilmName

                 }).ToList();
        return Json(new { data = q }, JsonRequestBehavior.AllowGet);
    }

adding my classes

namespace MoviePro.Models
{
using System;
using System.Collections.Generic;

public partial class Films
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", 
 "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Films()
    {
        this.Customers = new HashSet<Customers>();
    }

    public int FilmId { get; set; }
    public string FilmName { get; set; }
    public string Length { get; set; }
    public string Genre { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", 
    "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Customers> Customers { get; set; }
    }
    }
    public partial class Customers
    {
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", 
    "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Customers()
    {
        this.Films = new HashSet<Films>();
    }

    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public Nullable<int> FilmId { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", 
    "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Films> Films { get; set; }
    }
    }

thank you so much,

****New CODE THAT WORKS****

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MoviePro.Models;
using System.Data.Entity;

namespace MoviePro.Controllers
{
public class CustomersController : Controller
{
    // GET: Customers
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult GetData()
    {
        MyDatabaseEntities2 db = new MyDatabaseEntities2();
        var q = (from c in db.Customers
                 from Films in c.Films
                 where Films.FilmId == Films.FilmId
                 where c.CustomerId == c.CustomerId
                 select new
                 {
                     c.CustomerName,
                     c.Phone,
                     c.FilmId,
                     c.CustomerId,
                     FilmName = Films.FilmName

                 }).ToList();
        return Json(new { data = q }, JsonRequestBehavior.AllowGet);
    }

    public ActionResult loaddata()
    {
        MyDatabaseEntities2 dc = new MyDatabaseEntities2();

        var customers = dc.Customers.Select(c => new
        {
            c.CustomerName,
            c.Phone,
            c.FilmId,
            c.CustomerId,


        });

        return Json(new { data = customers }, JsonRequestBehavior.AllowGet);

    }

    public ActionResult AddOrEdit(int id = 0)
    {
        if (id == 0)
            return View(new Customers());

        else
        {
            using (MyDatabaseEntities2 db = new MyDatabaseEntities2())
            {
                return View(db.Customers.Where(x => x.CustomerId== 
   id).FirstOrDefault<Customers>());

            }
        }
    }

    [HttpPost]
    public ActionResult AddOrEdit(Customers customer)
    {
        using (MyDatabaseEntities2 db = new MyDatabaseEntities2())
        {
            if (customer.CustomerId == 0)
            { 
                db.Customers.Add(customer);
                db.SaveChanges();
                return Json(new { success = true, message = "Saved 
      Successfully" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                db.Entry(customer).State = EntityState.Modified;
                db.SaveChanges();
                return Json(new { success = true, message = "Updated 
        Successfully" }, JsonRequestBehavior.AllowGet);
            }
        }


    }

    [HttpPost]
    public ActionResult Delete(int id)
    {
        using (MyDatabaseEntities2 db = new MyDatabaseEntities2())
        {
            Customers emp = db.Customers.Where(x => x.CustomerId == 
      id).FirstOrDefault<Customers>();

            db.Customers.Remove(emp);
            db.SaveChanges();
            return Json(new { success = true, message = "Deleted 
       Successfully" }, JsonRequestBehavior.AllowGet);
        }
        }
       }
       }

回答1:


The basic LINQ query shape for querying many-to-many relationships is:

from c in db.Customers
from f in c.Films // NOT db.Films
select new
{
    Customer = c.Customername,
    Film = f.FilmName,
    ...
}

This is the query syntax equivalent of SelectMany. The result is a flat list of data, hence this is commonly referred to as "flattening".

Often it's more useful to show a nested list:

from c in db.Customers
select new
{
    c.Customername,
    c. ...,
    Films = from f in c.Films
            select new
            {
                f.FilmName,
                f. ...,
            }
}


来源:https://stackoverflow.com/questions/46926448/get-data-of-all-entities-in-a-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!