简体   繁体   中英

Entity Framework - not using linked table id in insert query

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; }
    ...
}

the SQL table ( with the FK constraint between the two tables ):

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

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

Cannot insert the value NULL into column 'SomeBarId ', table 'dbo.foo'; column does not allow nulls. INSERT fails.

how do I tell entity to use the field SomeBarId when doing the insert ?

var someBar = await _context.Bars.FindAsync(1); // fetch a Bar record

foo.SomeBar = someBar; // linking the objects

_context.Foo.Add(foo);

await _context.SaveChangesAsync(); 

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

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; }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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