Tôi đang sử dụng Khung thực thể để ánh xạ hai bảng với nhau bằng cách sử dụng Phân tách thực thể như được nêu here và here.Tại sao Entity Framework 5 truy vấn các bảng khác nhau khi thực hiện một .ToList() so với một .Count() trên cùng một thực thể?
Tôi đã nhận thấy rằng nếu tôi thực thi một số .ToList()
trên IQueryable<SplitEntity>
thì kết quả là từ Tham gia bên trong. Tuy nhiên, nếu tôi lấy cùng một IQueryable đó và thực thi một số .Count()
nó sẽ trả về số lượng các bản ghi được trả về bởi một Tham gia đầy đủ.
Dưới đây là một thử nghiệm đơn vị đó không:
[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.
}
này đập vào mắt tôi là rất xấu. Làm thế nào tôi có thể nhận được phương thức .Count()
để trả lại kết quả từ một Tham gia Nội bộ như .ToList()
?
Cập nhật - SQL
Tôi đã sai về sự tham gia đầy đủ so với bên trong.
Các ToList() kết quả trong:
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]
Các Count() kết quả trong:
SELECT
[GroupBy1].[A1] AS [C1]
FROM (SELECT
COUNT(1) AS [A1]
FROM [dbo].[customerTable2] AS [Extent1]
) AS [GroupBy1]
Update - DataContext và thực thể đang
Các 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());
}
}
}
Quy trình giám sát omer Mapping (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");
});
}
}
Thực thể của khách hàng:
public class Customer
{
[Key]
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
}
Bạn chưa cho chúng ta thấy các truy vấn nó tạo ra ... –
chúng ta cần xem ngữ cảnh. Khách hàng cần biết nhiều hơn. Nếu bạn thực hiện một truy vấn đơn giản thì bạn sẽ nhận được cùng một số tôi nghĩ. – phillip
Câu hỏi đã được cập nhật với mã ngữ cảnh và thực thể bổ sung. – quakkels