我正在使用實體框架來使用實體分割將兩個表映射到一起,如概述here和here。爲什麼實體框架5在同一實體上執行.ToList()與.Count()時查詢不同的表?
我發現如果我在IQueryable<SplitEntity>
上執行.ToList()
,則結果來自Inner Join。但是,如果我採用相同的IQueryable並執行.Count()
,它將返回完全連接返回的記錄數。
這是一個單元測試失敗:
[TestMethod]
public void GetCustomerListTest()
{
// arrange
List<Customer> results;
int count;
// act
using (var context = new DataContext())
{
results = context.Customers.ToList();
count = context.Customers.Count();
}
// assert
Assert.IsNotNull(results); // succeeds
Assert.IsTrue(results.Count > 0); // succeeds. Has correct records from inner join
Assert.AreEqual(count, results.Count); // This line fails. Has incorrect count from full join.
}
這令我非常糟糕。我怎樣才能讓.Count()
方法返回來自Inner Join的結果,如.ToList()
?
更新 - SQL
我對完整vs內連接錯了。
的.ToList()的結果:
SELECT
[Extent1].[CustomerNumber] AS [CustomerNumber],
-- ...etc...
[Extent2].[CustomerName] AS [CustomerName],
-- ... etc...
FROM [dbo].[CustomerTable1] AS [Extent1]
INNER JOIN [dbo].[CustomerTable2] AS [Extent2] ON [Extent1].[CustomerNumber] = [Extent2].[CustomerNumber]
的.Count之間()的結果:
SELECT
[GroupBy1].[A1] AS [C1]
FROM (SELECT
COUNT(1) AS [A1]
FROM [dbo].[customerTable2] AS [Extent1]
) AS [GroupBy1]
更新 - 的DataContext和實體代碼
在DataContext:
public class DataContext : DbContext
{
public DataContext() { Database.SetInitializer<DataContext>(null); }
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CustomerMapping());
}
}
}
The Cust奧馬爾映射(FluentAPI):
public class CustomerMapping : EntityTypeConfiguration<Customer>
{
public CustomerMapping()
{
this.Map(m => {
m.Properties(x => new { x.CustomerNumber, /*...etc...*/});
m.ToTable("CustomerTable1");
})
.Map(m => {
m.Properties(x => new { x.CustomerName, /*...etc...*/});
m.ToTable("CustomerTable2");
});
}
}
客戶實體:
public class Customer
{
[Key]
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
}
你還沒有告訴我們它生成的查詢... –
我們需要了解情況。客戶需要了解更多信息。如果你執行一個簡單的查詢,那麼你會得到相同的計數,我認爲。 – phillip
該問題已更新爲附加的上下文和實體代碼。 – quakkels