Sto cercando di aggiungere dati al database utilizzando EF Core, ma non riesco a superare un errore di chiave duplicato: Cannot insert duplicate key row in object 'dbo.Stocks' with unique index 'IX_Stocks_Name'. The duplicate key value is (stock1).
Ho uno Stock
entità che ha una relazione uno-a-molti con Transaction
- uno Stock
può essere correlato con molte Transaction
.
Il problema non si verifica solo se non c'è Stock
con un dato ID nel database - in quel caso posso aggiungere molte Transaction
s con lo stesso StockID
e funziona:
using(var context = dbContextFactory.CreateDbContext(new string[0]))
{
List<Transaction> list = new List<Transaction>();
//If there's no Stock with ID "stock1" in the database the code works.
//Executing the code for the second time results in error, however, if I changed stock1 to stock2 it would work
var stock1 = new Stock("stock1");
list.AddRange(new Transaction[]
{
//I can add two exactly the same `Transaction`s and it's ok when executed on a fresh database
new Transaction(stock1, DateTime.Now, 1M, 5),
new Transaction(stock1, DateTime.Now, 1M, 5),
});
context.Transactions.AddRange(list);
context.SaveChanges();
}
Di seguito ho aggiunto le definizioni delle classi con i loro IEntityTypeConfiguration
s.
Grazie in anticipo per eventuali suggerimenti.
Classe di Transaction
:
public class Transaction
{
public Stock RelatedStock { get; set; }
public DateTime TransactionTime { get; set; }
public Decimal Price { get; set; }
public int Volume { get; set; }
public Transaction() { }
}
Classe TransactionConfiguration
:
public class TransactionConfiguration : IEntityTypeConfiguration<Transaction>
{
public void Configure(EntityTypeBuilder<Transaction> builder)
{
builder
.ToTable("Transactions");
builder
.Property<int>("TransactionID")
.HasColumnType("int")
.ValueGeneratedOnAdd()
.HasAnnotation("Key", 0);
builder
.Property(transaction => transaction.Price)
.HasColumnName("Price")
.IsRequired();
builder
.Property(transaction => transaction.TransactionTime)
.HasColumnName("Time")
.IsRequired();
builder
.Property(transaction => transaction.Volume)
.HasColumnName("Volume")
.IsRequired();
builder
.HasIndex("RelatedStockStockID", nameof(Transaction.TransactionTime))
.IsUnique();
}
}
Classe di Stock
:
public class Stock
{
public string Name { get; set; }
public ICollection<Transaction> Transactions { get; set; }
public Stock() { }
}
Classe di StockConfiguration
:
public class StockConfiguration : IEntityTypeConfiguration<Stock>
{
public void Configure(EntityTypeBuilder<Stock> builder)
{
builder
.ToTable("Stocks");
builder
.Property<int>("StockID")
.HasColumnType("int")
.ValueGeneratedOnAdd()
.HasAnnotation("Key", 0);
builder
.Property(stock => stock.Name)
.HasColumnName("Name")
.HasMaxLength(25)
.IsRequired();
builder
.HasMany(stock => stock.Transactions)
.WithOne(transaction => transaction.RelatedStock)
.IsRequired();
builder
.HasIndex(stock => stock.Name)
.IsUnique();
}
}
C'è un indice univoco nella dbo.Stocks
tabella denominata IX_Stocks_Name
. Stai violando questo indice.
Il tuo problema è questa linea:
var stock1 = new Stock("stock1");
Stai creando "stock1" più e più volte. Invece, dovresti prima recuperare (o archiviare) l'entità Stock
per "stock1" e usarla, se esiste già. Se non esiste, è sicuro crearne uno.
In breve, il codice sta eseguendo un INSERT
in dbo.Stocks
con un Name
esistente.
Grazie ai suggerimenti di @ Zer0 e di @Steve Py ho trovato la seguente soluzione:
void Insert(IEnumerable<Transaction> data)
{
using(var context = dbContextFactory.CreateDbContext(new string[0]))
{
List<Stock> stocks = data.Select(s => s.RelatedStock).Distinct(new StockComparer()).ToList();
context.AddRange(stocks);
context.SaveChanges();
stocks = context.Stocks.ToList();
List<Transaction> newList = new List<Transaction>(data.Count());
foreach (var t in data)
{
Stock relatedStock = stocks.Where(s => s.Name == t.RelatedStock.Name).First();
t.RelatedStock = relatedStock;
newList.Add(t);
}
context.Transactions.AddRange(newList);
context.SaveChanges();
}
}