实体框架生成错误的SQL

时间:2017-04-18 01:28:43

标签: c# mysql entity-framework entity

我试图通过Entity Framework插入一条记录,看来生成的SQL不正确。我正在插入'PostingSelections'表。该表与其他三个表'PropertyPosting','PropertySummary'和'User'有FK。用户的FK可以为空。这是使用MySQL数据库,我怀疑是问题。

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);

我的代码是:

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();

当我自动生成控制器时,代码与entityframework自动生成的代码完全相同。 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()

看看它是如何两次生成三列的? PropertyPosting_Id,PropertyPosting_Id和User_Id?按预期生成的错误是:

  

71 ms失败,错误:列'User_Id'指定了两次

有人可以帮忙吗?这是一个非常基本的插入,我找不到任何其他类似的帖子。我只能得出结论,我在EF for mySQL中发现了一个错误,并且必须使用手动SQL语句来执行此操作。

1 个答案:

答案 0 :(得分:1)

我几天前遇到过类似的问题,我认为它与“主要选择”的主键有关。" PostingSelections"表。

尝试为您的表指定PK,否则EF不会区分记录。

相关问题