简体   繁体   English

实体框架生成错误的SQL

[英]Entity framework generating wrong SQL

I am attempting to insert a record through Entity Framework and it appears the SQL generated is incorrect. 我正在尝试通过Entity Framework插入一条记录,并且看来生成的SQL不正确。 I am inserting into the 'PostingSelections' table. 我要插入“ PostingSelections”表。 This table has FK's to three other tables 'PropertyPosting', 'PropertySummary' and 'User'. 该表具有FK到其他三个表'PropertyPosting','PropertySummary'和'User'。 The FK to User is nullable. 用户的FK为空。 This is using a MySQL database, which I am suspicious is the problem. 这是使用MySQL数据库,我怀疑这是问题所在。

The DDL for the PostingSelections table is: PostingSelections表的DDL为:

CREATE TABLE `PostingSelections`(
    `Id` int NOT NULL AUTO_INCREMENT UNIQUE, 
    `SelectionType` TINYINT UNSIGNED NOT NULL, 
    `Date` datetime NOT NULL, 
    `SourceIPAddress` longtext NOT NULL, 
    `PropertyPosting_Id` int NOT NULL, 
    `PropertySummary_Id` int NOT NULL, 
    `User_Id` int);

My code is: 我的代码是:

var postingselection = new postingselection();
postingselection.PropertyPosting_Id = 24;
postingselection.PropertySummary_Id = 24;  
postingselection.SelectionType = 1;  
postingselection.Date = DateTime.UtcNow;  
postingselection.SourceIPAddress = "TBD";   

db.postingselections.Add(postingselection);
db.SaveChanges();

The code is exactly the same as what is automatically generated by entityframework when I generate the controller automatically. 该代码与当我自动生成控制器时由entityframework自动生成的代码完全相同。 The SQL that EF is generating is: EF生成的SQL是:

INSERT INTO `postingselections`(
`SelectionType`, 
`Date`, 
`SourceIPAddress`, 
`PropertyPosting_Id`, 
`PropertySummary_Id`, 
`User_Id`, 
`propertyposting_Id`, 
`propertysummary_Id`, 
`user_Id`) VALUES (
1, 
4/18/2017, 
TBD, 
24, 
24, 
0, 
24, 
24, 
NULL);
SELECT
`Id`
FROM `postingselections`
 WHERE  row_count() > 0 AND `Id`=last_insert_id()

See how it has generated three columns twice? 看看它是如何两次生成三列的? PropertyPosting_Id, PropertyPosting_Id and User_Id? PropertyPosting_Id,PropertyPosting_Id和User_Id? The error that is generated as expected is: 按预期生成的错误是:

Failed in 71 ms with error: Column 'User_Id' specified twice 在71毫秒内失败,并出现以下错误:列“ User_Id”指定了两次

Could someone please help? 有人可以帮忙吗? This is a very basic insert, and I can't find any other similar postings. 这是一个非常基本的插入内容,我找不到其他类似的帖子。 I can only conclude I have found a bug in EF for mySQL and will have to do this instead with a manual SQL statement. 我只能得出结论,我已经在EF中找到了mySQL的错误,因此必须使用手动SQL语句来完成。

I encountered a similar problem few days ago, I think it's related to the the Primary Key of "PostingSelections" table. 几天前,我遇到了类似的问题,我认为它与“ PostingSelections”表的主键有关。

Try to specify a PK for your table, otherwise EF wont differentiate the records. 尝试为您的表指定一个PK,否则EF不会区分记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM