实体框架-在插入查询中不使用链接表ID [英] Entity Framework - not using linked table id in insert query
本文介绍了实体框架-在插入查询中不使用链接表ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个表Foo和Bar, Foo有指向条记录的链接
I have 2 tables, Foo and Bar, Foo has a link to a Bar record
public class Foo
{
public int Id { get; set; }
public Bar SomeBar{ get; set; }
}
public class Bar
{
public int? Id { get; set; }
...
}
SQL表(两个表之间具有FK约束):
CREATE TABLE [dbo].[Foo] (
[Id] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[SomeBarId] INT NOT NULL,
CONSTRAINT [FK_Foo_Bar] FOREIGN KEY ([SomeBarId]) REFERENCES [Bar]([Id]),
);
当我保存表时,实体未在查询中使用SomeBarId ,这会产生错误,而我已在两个表之间设置了 FK约束
when I save the table, Entity does not use SomeBarId in the query, producing an error, while I have set a FK constraint between the two tables
无法将值NULL插入表'dbo.foo'的列'SomeBarId'中;列不允许为空.INSERT失败.
我如何告诉实体在执行插入操作时使用SomeBarId字段?
var someBar = await _context.Bars.FindAsync(1); // fetch a Bar record
foo.SomeBar = someBar; // linking the objects
_context.Foo.Add(foo);
await _context.SaveChangesAsync();
我希望EF在数据库中插入Foo时获得EF的someBar.Id并在查询中使用它
I expect EF to get someBar.Id and use it in the query when inserting Foo in DB
感谢您在帮助我上花费的时间
thanks for the time you'll spend helping me on this
推荐答案
尝试在Foo类中添加ForeignKey属性,并在Bar中删除可为空的ID
Try adding ForeignKey attribute in class Foo and remove the nullable Id in Bar
public class Foo
{
[ForeignKey("Bar")]
public int Id { get; set; }
public Bar SomeBar{ get; set; }
}
public class Bar
{
public int Id { get; set; }
...
}
这篇关于实体框架-在插入查询中不使用链接表ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文