当我尝试执行预先加载(.WithXyz()
方法)时,我得到了错误的数据。它尝试使用两个表的主 ID 进行连接,而不是将主表上的“属性”连接到辅助表的 ID。
这是我的代码、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');
最佳答案
看起来(来自 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,以便显式连接起作用。
关于c# - 如何在 Simple.Data 中正确执行预加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15145482/