从2个表中选择所有记录 - 多对多EF C#

时间:2018-03-09 13:24:23

标签: c# asp.net-mvc entity-framework linq many-to-many

我的MVC 5应用程序中有2个表

public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? Birthdate { get; set; }
}

public class Movie
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime ReleaseDate { get; set; }
}

联合表租借用于多对多关系

public class Rental
{
    public int Id { get; set; }

    [Required]
    public Customer Customer { get; set; }

    [Required]
    public Movie Movie { get; set; }

    public DateTime? DateReturned { get; set; }
}

租用表在填充时看起来像这样(只有来自电影和客户PK的ID):

Table Rental

如何从我的HomeController中的那两个表(或一个联合租赁)中选择所有记录(只是让客户名称及其所有电影)到一个表中?

1 个答案:

答案 0 :(得分:0)

ICollection<Rental> Rentals实体添加导航属性(Customer)以表示Rentals个实体。

public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? Birthdate { get; set; }

    public ICollection<Rental> Rentals { get; set; }
}

按客户查询所有电影;

var result = dbo.Customers.Select(x => new CustomerDto
{
    Name = x.Name,
    Movies = x.Rentals.Select(k => k.Movie)
});