使用LINQ方法语法从多个表返回数据

时间:2018-04-06 08:57:23

标签: asp.net-mvc entity-framework linq

我的数据库返回数据有问题。在我的数据库中有三个表:Customer,Activity和CustomerActivity。我想返回特定客户和特定类型活动的活动数据。我写了查询,但它并没有完全按照我的意愿工作。这是我的代码和表格。谢谢你的建议。

var activities = db.Join(db.CustomerActivities, a => a.ActivityID, ca =>ca.CustomerActivityID, (a, ca) => new { Activity = a, CustomerActivity = ca })
    .Where(a => a.CustomerActivity.customer.CustomerID == id && a.Activity.TypeActivityID == typeActivity)
    .Select(m => new ActivityMV()
    {
        ActivityID = m.Activity.ActivityID,
        Name = m.Activity.Name,
        DateOfActivity = m.Activity.DateOfActivity,
        Desc = m.Activity.Desc
    })
    .ToList();


public class CustomerActivity
{
    public int CustomerActivityID { get; set; }
    public int CustomerID { get; set; }
    public int ActivityID { get; set; }
    public virtual Customer customer { get; set; }
    public virtual Activity activity { get; set; }
}
public class Activity
{
    public int ActivityID { get; set; }
    public string Name { get; set; }
    public string Desc { get; set; }
    public string DateOfActivity { get; set; }
    public string TypeActivityID { get; set; }
    public virtual ICollection <CustomerActivity> customerActivities { get; set; }
}

1 个答案:

答案 0 :(得分:1)

尝试

var activities = db.CustomerActivities
.Where(ca => ca.CustomerID == id && ca.Activity.TypeActivityID == typeActivity)
.Select(ca => new ActivityMV()
{
    ActivityID = ca.ActivityID,
    Name = ca.Activity.Name,
    DateOfActivity = ca.Activity.DateOfActivity,
    Desc = ca.Activity.Desc
})
.ToList();