2013-02-28 44 views
1

當我嘗試做一個急切的加載(.WithXyz()方法)時,我得到了錯誤的數據。它嘗試使用兩個表的主Id進行連接,而不是主表上的「屬性」連接到輔助表的Id。如何在Simple.Data中正確執行加載?

這是我的代碼,在Simple.Data.MySql,或在Simple.Data中的錯誤?

我使用NuGet的Simple.Data(0.18.3.1)和Simple.Data.MySql(0.18.3.0)的版本。

我的代碼:

var traceListener = new SimpleDataTraceListener(); // For logging SQL 
Trace.Listeners.Add(traceListener); 

var db = Database.Open(); 
OrderItem orderItem = db.OrderItems 
    .WithCustomer() 
    .Get(1) 
    ; 

Console.WriteLine(traceListener.Output); 
Console.WriteLine(orderItem.Customer.FullName); 

下面是SQL的一個例子,我希望:

SELECT orderitem.id, 
     orderitem.customer_Id, 
     orderitem.productname, 
     customer.id AS __with1__Customer__id, 
     customer.fullname AS __with1__Customer__fullname 
FROM orderitem 
LEFT JOIN customer ON (orderitem.customer_Id = customer.id) 
WHERE orderitem.id = ?p1 LIMIT 0, 1 

?p1 (UInt64) = 1 

這裏是它實際上是創建SQL的日誌:

select orderitem.id, 
     orderitem.customer_Id, 
     orderitem.productname, 
     customer.id AS __with1__Customer__id, 
     customer.fullname AS __with1__Customer__fullname 
from orderitem 
LEFT JOIN customer ON (orderitem.id = customer.id) 
WHERE orderitem.id = ?p1 LIMIT 0, 1 

?p1 (UInt64) = 1 

我的數據:

CREATE TABLE `customer` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT, 
    `fullname` VARCHAR(130) NOT NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE INDEX `fullname_UNIQUE` (`fullname` ASC) 
); 

CREATE TABLE `orderitem` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT, 
    `customer_Id` BIGINT(20) NOT NULL, 
    `productname` VARCHAR(130) NOT NULL, 
    PRIMARY KEY (`id`), 
    FOREIGN KEY (`customer_Id`) REFERENCES `customer` (`id`) 
); 

INSERT INTO `customer` (fullname) 
VALUES ('wall-E'), ('merlyn'), ('someone'); 

INSERT INTO `orderitem` (customer_Id, productName) 
VALUES (3, 'test item 1'), (2, 'test item 2'), (1, 'test item 3'); 

回答

2

它看起來像(從https://github.com/Vidarls/Simple.Data.Mysql/blob/master/Src/Simple.Data.Mysql.Mysql40/MysqlForeignKeyCreator.cs)就像MySQL提供程序處理外鍵的方式可能存在問題。該提供者是爲MySQL 4.0編寫的;自該版本以來,語法可能發生了相當大的變化

我建議在該項目的GitHub頁面上提出一個問題(https://github.com/Vidarls/Simple.Data.Mysql/issues),或者如果可以的話,也許可以幫助提出請求。

在此期間,你可以明確地加入這樣的:

var db = Database.Open(); 
dynamic customer; 
OrderItem orderItem = db.OrderItems 
    .FindAllById(1) 
    .OuterJoin(db.Customers.As("Customer"), out customer) 
    .On(Id: db.OrderItems.CustomerId) 
    .With(customer) 
    .FirstOrDefault(); 

我也改爲使用查詢和FirstOrDefault代碼,使顯式連接工程。