0

I am trying to use the bulk insert feature. My model looks like this:

public class Stockprice
{
    [Key]
    public int Id { get; set; }
    
    [Required]
    [LinqToDB.Mapping.Association(ThisKey = "StockId", OtherKey = "Id")]
    public Stock Stock { get; set; }
    
    //some more
}

public class MinuteStockprice : Stockprice { }

The code insert code:

private async Task SavePrices<T>(List<Quote> quotes) where T : Stockprice, new()
{
    using var context = _factory.CreateDbContext();
    var connection = context.CreateLinqToDbConnection();
    connection.TraceSwitchConnection.Level = TraceLevel.Verbose;
    connection.OnTraceConnection = x => Console.WriteLine(x.SqlText);
    var stocks = new List<T>();
    foreach (var quote in quotes)
    {
        var price = new T { Stock = new Stock() { Id = _isinToStockId[quote.Isin] }, Ask = quote.Ask, Bid = quote.Bid, Time = quote.Time };
        stocks.Add(price);
        context.Stocks.Attach(price.Stock);
    }
    await connection.BulkCopyAsync(stocks);
    //await context.BulkCopyAsync(stocks);
}

Not sure what I am missing, but it doesn't insert the StockId. This is the head of the generated Sql:

INSERT INTO [MinuteStockprices]
(
        [Time],
        [Ask],
        [Bid]
)

How do I include the StockId here?

EDIT

The table is created like this:

CREATE TABLE "MinuteStockprices" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_MinuteStockprices" PRIMARY KEY AUTOINCREMENT,
    "StockId" INTEGER NOT NULL,
    "Bid" REAL NOT NULL,
    "Ask" REAL NOT NULL,
    "Time" TEXT NOT NULL,
    CONSTRAINT "FK_MinuteStockprices_Stocks_StockId" FOREIGN KEY ("StockId") REFERENCES "Stocks" ("Id") ON DELETE CASCADE
)
tailoxyn
  • 120
  • 9

1 Answers1

0

BulkCopy is low level command which inserts into ONE table and only in one table. If you need to insert details, you have to do that separately.

Also check that class has StockId property, because shadow properties are not supported.

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
  • If I add the StockId property even with an [NotMapped] Attribute or Ignore it using the OnModelCreating Method of my DbContext, i recieve a warning: "Microsoft.EntityFrameworkCore.Model.Validation[10625] The foreign key property 'MinuteStockprice.StockId1' was created in shadow state because a conflicting property with the simple name 'StockId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type. See https://aka.ms/efcore-relationships for information on mapping relationships in EF Core." – tailoxyn Aug 09 '22 at 09:28
  • And EF Core will try to use this in following requests: : "SQLite Error 1: 'no such column: h.StockId1'." – tailoxyn Aug 09 '22 at 09:29
  • It is not right place for question how to map ForeignKey in EF Core. – Svyatoslav Danyliv Aug 09 '22 at 09:33