我收到了以下错误,尽管在许多“类似”帖子上进行了跟踪,但在使用 Entity Framework 向FK插入2个表时,我找不到答案。我认为问题是,当查看Trace / Log(下面)时,FK(id)值为0(零)。如果我能弄清楚这可能会解决问题。
错误:(明显是什么意思,但无法弄清楚如何解决)
无法添加或更新子行:外键约束失败(“xdata”。“table_b”,CONSTRAINT“f111”FOREIGN KEY(“table_a_id”)REFERENCES“table_a”(“id”)ON DELETE CASCADE ON UPDATE CASCADE)
模型:
public class table_a
{
public int id { get; set; }
public string name { get; set; }
}
public class table_b
{
public int id { get; set; }
public string desc { get; set; }
public int table_a_id { get; set; }
}
代码模拟和插入代码:
table_a a = new table_a()
{
name = "table a name",
};
table_b b = new table_b()
{
desc = "table b desc",
table_a_id = a.id
};
DataContext.Database.Log = message => Trace.Write(message);
DataContext.TableA.Add(a);
DataContext.TableB.Add(b);
var result = DataContext.SaveChanges();
TRACE:
SET SESSION sql_mode ='ANSI';
INSERT INTO table_a
(
name
)价值观(
@ GP1);
选择
id
来自table_a
WHERE row_count()> 0 AND id
= last_insert_id()
- @ gp1:'table a name'(Type = String,IsNullable = false,Size = 12)
- 执行时间为12/8/2017 7:50:53 PM -07:00
- 在55 ms内完成,结果为:EFMySqlDataReader
SET SESSION sql_mode ='ANSI';
INSERT INTO table_b
(
desc
,
table_a_id
)价值观(
@ GP1,
的 0 );
选择
id
来自table_b
WHERE row_count()> 0 AND id
= last_insert_id()
- @ gp1:'table b desc'(Type = String,IsNullable = false,Size = 12)
- 执行时间为12/8/2017 7:50:53 PM -07:00
- 56 ms失败并出现错误:无法添加或更新子行:外键约束失败(“xdata”。“table_b”,CONSTRAINT“f111”FOREIGN KEY(“table_a_id”)REFERENCES“table_a”(“id” )ON UPETE CASCADE ON UPDATE CASCADE)
DB SCHEMA: 编辑删除数据库架构图像(12/8/2017)
CREATE TABLE `table_a`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `table_b`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`desc` varchar(45) DEFAULT NULL,
`table_a_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `f111_idx` (`table_a_id`),
CONSTRAINT `f111` FOREIGN KEY (`table_a_id`) REFERENCES `table_a` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;