1

I have got problem with return data from my database. In my database are three tables: Customer, Activity and CustomerActivity. I want to return activities data for specific customer and with specific type activity. I wrote query but it doesn't work exactly as I wish. Here is my code and tables. Thank you for advices.

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; }
}
3
  • "I wrote query but it doesn't work exactly as I wish." What is your actual result vs. your expected result? Commented Apr 6, 2018 at 9:09
  • There is no need of joins (db.Join(...) is not a valid construct anyway). Start the query from db.CustomerActivities and simply use CustomerActivity navigation properties (Customer and Activity) in Where and Select expressions. Commented Apr 6, 2018 at 9:11
  • To method I send two parameters: customer Id and type of activity. I want to get all activities for customer with specific type. I add that same data for two users and once in two different cases I get two diffrent results Commented Apr 6, 2018 at 9:21

1 Answer 1

1

Try

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh, it works perfectly. One trifle: .Select(ca => new ActivityMV() Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.