【发布时间】:2017-04-18 16:43:48
【问题描述】:
我正在尝试通过实体框架插入一条记录,但生成的 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 毫秒内失败并出现错误:列 'User_Id' 指定了两次
有人可以帮忙吗?这是一个非常基本的插入,我找不到任何其他类似的帖子。我只能得出结论,我在 EF for mySQL 中发现了一个错误,因此必须使用手动 SQL 语句来代替。
【问题讨论】:
-
你的实体对象是什么样子的?
-
可能是用户 ID 在对象中不可为空。如果是这种情况,它应该是类似 int 的东西?用户 ID { 获取;放; }
-
由于所有 3 个重复字段都与外键 (FK) 相关,因此它们与不可为空的列之间的一对多关系似乎会触发问题。尝试对所有 FK 使用可为空的值类型。
-
发布您的完整实体模型。并显示导航属性
标签: c# mysql entity-framework entity