I have Linq to sql as shown below:
var members=db.Members.Include(x=> x.Contact).Count();
Now, due to some bad data, all contacts in my members do not have the corresponding Contact record. So, during the count, how can I include the graph after Inner Join in the contact table.
The problem is when I get the member list, the member list has 100 entries , and Count has 150 entries (50 entries are bad data) .
var membersQ=db.Members.Include(x=> x.Contact).Select(i=> new MemberViewModel(){ Name = i.Contact.Name, ContactId= i.Contact.Id, CreatedDate= i.CreatedDate }).AsQueryable(); var members=memberQ.ToList();
I checked the final query while counting, apparently it doesn’t do JOIN with the contact table, but Count()
Database structure update
Member Table Id ContactId, CompanyId, CreatedDate ... Contact Table Id Name ...
The foreign key for ContactId in the Member table is not set at the database level, but only on the model.
[ForeignKey("ContactId")] Public Contact Contact { get; set; }
Bad data looks like
I used to have 1,2,3,4,5,6,7,8,9,10 as Contact entries, and all these contacts were also in the Member table.
Now I deleted the entries from the contact table, say, 6-10. But it was not deleted from the Member table.
So this causes a problem with the counter. I'm sure deleting bad data from Member solves the problem, but the question is how to use join while using Count() .
Note. I am using a null database initializer
Update 2 I used LinqPad and tried both the default Linq To SQL and EntityFramework (DbContext), and what I found is confusing.
For request:
(from a in Members join b in Contacts on a.ContactId equals b.ContactId select a).Count()
Using Linq for SQL by default
SELECT COUNT(*) AS [value] FROM [Member] AS [t0] INNER JOIN [Contact] AS [t1] ON [t0].[ContactID] = [t1].[ContactID]
Using Entityframework DbContext
SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[Member] AS [Extent1] ) AS [GroupBy1]
In my code, I use the DbContext method. So ... I don't know what to do here, btw: Sorry for the presence of the linq-to-sql tag, actually EntityFramework