Hello friends! Here are my entities:
public class Subscription
{
[Key]
public int id { get; set; }
public string name { get; set; }
public double data { get; set; }
}
public class SubscriptionData
{
[Key]
public int id { get; set; }
[ForeignKey("subscription")]
public int subscriptionId { get; set; }
public virtual Subscription subscription { get; set; }
[ForeignKey("company")]
public int companyId { get; set; }
public virtual Company company { get; set; }
public double price { get; set; }
}
public class Company
{
[Key]
public int id { get; set; }
public string name { get; set; }
public ICollection<Client> clients { get; set; }
public ICollection< SubscriptionData > subscriptions { get; set; }
}
public class Client
{
[Key]
public int id { get; set; }
[ForeignKey("company")]
public int companyId { get; set; }
public virtual Company company { get; set; }
[ForeignKey("subscription")]
public int? subscriptionId { get; set; }
public virtual Subscription subscription { get; set; }
public string name { get; set; }
}
There is. a
SubscriptionData
wrapper because every company can have multiple prices for the same subscription.
Now, I am trying to just return list of clients with some calculated values.
I have it like this:
What I have tried:
I start with IQueryable<company> companies, this is returned by repository, and then do this:
companies
.Include(company => company.clients).ThenInclude(client => client.subscription)
.Include(company => company.clients).ThenInclude(client => client.company).ThenInclude(company => company.subscriptions).ThenInclude(data => data.subscription)
.Include(company => company.subscriptions).ThenInclude(data => data.subscription)
.Select(company => company.clients
.Select(client => new
{
proposedSubscription = client.company.subscriptions.FirstOrDefault(data => data.subscription.data < client.subscription.data)
}))
So I want to return all clients, with a new proposed subscription, which has less data then current client's subscription. I have one company and this company has 194 users. This condition:
proposedSubscription = client.company.subscriptions.FirstOrDefault(data => data.subscription.data < client.subscription.data)
is met for 4 clients.
But instead of getting 194 clients with 4 proposed subscriptions and rest of them with proposed subscriptions set to null, I get only 4 clients returned.
If I change the condition to:
proposedSubscription = client.company.subscriptions.FirstOrDefault(data => data.subscription.data < 10000)
I get then 194 clients, 4 with proposed subscription object and rest with proposed subscription object set to null.
I do not understand this behaviour of LINQ 2 SQL.
Can someone please explain what I am doing wrong?