C
C#2mo ago
ApathyErr

✅ WPF. Instance with the same key value for {'Id'} is already being tracked

I have two datagrids. They are filled with data from the database in this way:
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
var ord = from order in db.Orders
where order.Completed == 0
select new OrdView
{
oId = order.Id,
oNum = order.Num,
oData = order.Data,
oCustomersMail = order.CustomersMail,
oStartPoint = order.StartPoint,
oFinalPoint = order.FinalPoint,
oTrackNumber = order.TrackNumber,
oOrderStatus = order.OrderStatus,
oComment = order.Comment,
oMoneyPerOrder = order.MoneyPerOrder,
oCompleted = order.Completed
};
activeOrdersGrid.ItemsSource = ord.ToList();
}
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
var ord = from order in db.Orders
where order.Completed == 0
select new OrdView
{
oId = order.Id,
oNum = order.Num,
oData = order.Data,
oCustomersMail = order.CustomersMail,
oStartPoint = order.StartPoint,
oFinalPoint = order.FinalPoint,
oTrackNumber = order.TrackNumber,
oOrderStatus = order.OrderStatus,
oComment = order.Comment,
oMoneyPerOrder = order.MoneyPerOrder,
oCompleted = order.Completed
};
activeOrdersGrid.ItemsSource = ord.ToList();
}
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
var ord = from order in db.Orders
where order.Completed == 1
select new OrdView
{
oNum = order.Num,
oData = order.Data,
oCustomersMail = order.CustomersMail,
oStartPoint = order.StartPoint,
oFinalPoint = order.FinalPoint,
oTrackNumber = order.TrackNumber,
oOrderStatus = order.OrderStatus,
oComment = order.Comment,
oMoneyPerOrder = order.MoneyPerOrder,
oCompleted = order.Completed
};
completedOrdersGrid.ItemsSource = ord.ToList();
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
var ord = from order in db.Orders
where order.Completed == 1
select new OrdView
{
oNum = order.Num,
oData = order.Data,
oCustomersMail = order.CustomersMail,
oStartPoint = order.StartPoint,
oFinalPoint = order.FinalPoint,
oTrackNumber = order.TrackNumber,
oOrderStatus = order.OrderStatus,
oComment = order.Comment,
oMoneyPerOrder = order.MoneyPerOrder,
oCompleted = order.Completed
};
completedOrdersGrid.ItemsSource = ord.ToList();
49 Replies
ApathyErr
ApathyErr2mo ago
there are also buttons that cause an error when pressed:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var items = activeOrdersGrid.ItemsSource;
if (items != null)
{
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
// Get all records from the table
var allRecords = db.Orders.ToList();
// Delete all entries
//db.Orders.RemoveRange(allRecords);
// Save changes
db.SaveChanges();

// Go through all the records and add or update them in the database
foreach (var item in items)
{

Order order = new Order
{
Num = ((OrdView)item).oNum,
Data = ((OrdView)item).oData,
CustomersMail = ((OrdView)item).oCustomersMail,
StartPoint = ((OrdView)item).oStartPoint,
FinalPoint = ((OrdView)item).oFinalPoint,
TrackNumber = ((OrdView)item).oFinalPoint,
OrderStatus = ((OrdView)item).oOrderStatus,
Comment = ((OrdView)item).oComment,
MoneyPerOrder = ((OrdView)item).oMoneyPerOrder,
Completed = ((OrdView)item).oCompleted
};

db.Orders.Add(order); // Adding a new entry to the database
db.SaveChanges(); // Saving changes


}
}
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var items = activeOrdersGrid.ItemsSource;
if (items != null)
{
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
// Get all records from the table
var allRecords = db.Orders.ToList();
// Delete all entries
//db.Orders.RemoveRange(allRecords);
// Save changes
db.SaveChanges();

// Go through all the records and add or update them in the database
foreach (var item in items)
{

Order order = new Order
{
Num = ((OrdView)item).oNum,
Data = ((OrdView)item).oData,
CustomersMail = ((OrdView)item).oCustomersMail,
StartPoint = ((OrdView)item).oStartPoint,
FinalPoint = ((OrdView)item).oFinalPoint,
TrackNumber = ((OrdView)item).oFinalPoint,
OrderStatus = ((OrdView)item).oOrderStatus,
Comment = ((OrdView)item).oComment,
MoneyPerOrder = ((OrdView)item).oMoneyPerOrder,
Completed = ((OrdView)item).oCompleted
};

db.Orders.Add(order); // Adding a new entry to the database
db.SaveChanges(); // Saving changes


}
}
}
}
error:
System.InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
System.InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
leowest
leowest2mo ago
Change
private void
private void
to
private async void
private async void
And use FindAsync first:
var entry = await db.Orders.FindAsync(((OrdView)item).Id);
var entry = await db.Orders.FindAsync(((OrdView)item).Id);
use entry to update the fields, it will be tracked then savechanges instead of instanciating a new order unless entry is null meaning it did not find that id u should also not use the entities directly in your viewmodel / view code behind u should use DTOs but I suppose this is a simple enough app to forgive that?!
ApathyErr
ApathyErr2mo ago
✨ thx
leowest
leowest2mo ago
$close
MODiX
MODiX2mo ago
Use the /close command to mark a forum thread as answered
ApathyErr
ApathyErr2mo ago
I updated the code taking into account the recommendations and it does save changes to the record, but when trying to create a new record, the same error pops up
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
var items = activeOrdersGrid.ItemsSource;
if (items != null)
{
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
// Go through all the records and add or update them in the database
foreach (var item in items)
{
var entry = await db.Orders.FindAsync(((OrdView)item).oId);
if (entry != null)
{
// Update the entity using its primary key
}
else
{
Order order = new Order
{
// Set the properties of the new order entity
};

db.Orders.Add(order); // Adding a new entry to the database
}

await db.SaveChangesAsync(); // Saving changes
}
}
}
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
var items = activeOrdersGrid.ItemsSource;
if (items != null)
{
using (ProfitCalculatorDataBaseContext db = new ProfitCalculatorDataBaseContext())
{
// Go through all the records and add or update them in the database
foreach (var item in items)
{
var entry = await db.Orders.FindAsync(((OrdView)item).oId);
if (entry != null)
{
// Update the entity using its primary key
}
else
{
Order order = new Order
{
// Set the properties of the new order entity
};

db.Orders.Add(order); // Adding a new entry to the database
}

await db.SaveChangesAsync(); // Saving changes
}
}
}
}
leowest
leowest2mo ago
normally u dont define the id your self its handled by the db unless u changed it to manual so u wouldn't set the id also u can move the SaveChanges outside the foreach u dont need to save per entry u can save at the end
ApathyErr
ApathyErr2mo ago
// Update the entity using its primary key
entry.Num = ((OrdView)item).oNum;
entry.Data = ((OrdView)item).oData;
entry.CustomersMail = ((OrdView)item).oCustomersMail;
entry.StartPoint = ((OrdView)item).oStartPoint;
entry.FinalPoint = ((OrdView)item).oFinalPoint;
entry.TrackNumber = ((OrdView)item).oFinalPoint;
entry.OrderStatus = ((OrdView)item).oOrderStatus;
entry.Comment = ((OrdView)item).oComment;
entry.MoneyPerOrder = ((OrdView)item).oMoneyPerOrder;
entry.Completed = ((OrdView)item).oCompleted;
entry.Num = ((OrdView)item).oNum;
entry.Data = ((OrdView)item).oData;
entry.CustomersMail = ((OrdView)item).oCustomersMail;
entry.StartPoint = ((OrdView)item).oStartPoint;
entry.FinalPoint = ((OrdView)item).oFinalPoint;
entry.TrackNumber = ((OrdView)item).oFinalPoint;
entry.OrderStatus = ((OrdView)item).oOrderStatus;
entry.Comment = ((OrdView)item).oComment;
entry.MoneyPerOrder = ((OrdView)item).oMoneyPerOrder;
entry.Completed = ((OrdView)item).oCompleted;
// Set the properties of the new order entity
Num = ((OrdView)item).oNum,
Data = ((OrdView)item).oData,
CustomersMail = ((OrdView)item).oCustomersMail,
StartPoint = ((OrdView)item).oStartPoint,
FinalPoint = ((OrdView)item).oFinalPoint,
TrackNumber = ((OrdView)item).oFinalPoint,
OrderStatus = ((OrdView)item).oOrderStatus,
Comment = ((OrdView)item).oComment,
MoneyPerOrder = ((OrdView)item).oMoneyPerOrder,
Completed = ((OrdView)item).oCompleted
Num = ((OrdView)item).oNum,
Data = ((OrdView)item).oData,
CustomersMail = ((OrdView)item).oCustomersMail,
StartPoint = ((OrdView)item).oStartPoint,
FinalPoint = ((OrdView)item).oFinalPoint,
TrackNumber = ((OrdView)item).oFinalPoint,
OrderStatus = ((OrdView)item).oOrderStatus,
Comment = ((OrdView)item).oComment,
MoneyPerOrder = ((OrdView)item).oMoneyPerOrder,
Completed = ((OrdView)item).oCompleted
leowest
leowest2mo ago
is Num your Key? what is your entity like the class
ApathyErr
ApathyErr2mo ago
oId its key
leowest
leowest2mo ago
ah my bad I missed the oId
ApathyErr
ApathyErr2mo ago
namespace ProfitCalculator;

public partial class Order
{
public int Id { get; set; }

public int? Num { get; set; }

public string? Data { get; set; }

public string? CustomersMail { get; set; }

public string? StartPoint { get; set; }

public string? FinalPoint { get; set; }

public string? TrackNumber { get; set; }

public string? OrderStatus { get; set; }

public string? Comment { get; set; }

public double? MoneyPerOrder { get; set; }

public double? Expenses { get; set; }

public int? Completed { get; set; }
}
internal class OrdView
{
public int? oId { get; set; }
public int? oNum { get; set; }

public string? oData { get; set; }

public string? oCustomersMail { get; set; }

public string? oStartPoint { get; set; }

public string? oFinalPoint { get; set; }

public string? oTrackNumber { get; set; }

public string? oOrderStatus { get; set; }

public string? oComment { get; set; }

public double? oMoneyPerOrder { get; set; }

public double? oExpenses { get; set; }

public double? oProfit { get; set; }
public int? oCompleted { get; set; }

}
namespace ProfitCalculator;

public partial class Order
{
public int Id { get; set; }

public int? Num { get; set; }

public string? Data { get; set; }

public string? CustomersMail { get; set; }

public string? StartPoint { get; set; }

public string? FinalPoint { get; set; }

public string? TrackNumber { get; set; }

public string? OrderStatus { get; set; }

public string? Comment { get; set; }

public double? MoneyPerOrder { get; set; }

public double? Expenses { get; set; }

public int? Completed { get; set; }
}
internal class OrdView
{
public int? oId { get; set; }
public int? oNum { get; set; }

public string? oData { get; set; }

public string? oCustomersMail { get; set; }

public string? oStartPoint { get; set; }

public string? oFinalPoint { get; set; }

public string? oTrackNumber { get; set; }

public string? oOrderStatus { get; set; }

public string? oComment { get; set; }

public double? oMoneyPerOrder { get; set; }

public double? oExpenses { get; set; }

public double? oProfit { get; set; }
public int? oCompleted { get; set; }

}
leowest
leowest2mo ago
so u dont set the oId when u instatiate it right
ApathyErr
ApathyErr2mo ago
+
leowest
leowest2mo ago
do u have a builder instructions Order in your context? it should by default assume Id is the auto increment primary key by entity rules can u post the error message when u create a new instance?
ApathyErr
ApathyErr2mo ago
System.InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values."
System.InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values."
leowest
leowest2mo ago
are u using sqlite or some other db engine
ApathyErr
ApathyErr2mo ago
sqlite
leowest
leowest2mo ago
do u have any tool to open ur sqlite? I wonder if its not updatingautoincrementing the key
ApathyErr
ApathyErr2mo ago
I added the auto-generation id, but did not update the context in the program itself. Now I have done it and it has removed this error, but new records are still not saved.
leowest
leowest2mo ago
No description
ApathyErr
ApathyErr2mo ago
db browser
leowest
leowest2mo ago
u want to check if your column was properly created like that so your Id would have INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT next to it when u collapse the table
ApathyErr
ApathyErr2mo ago
No description
leowest
leowest2mo ago
u dont need unique but u do need not null
leowest
leowest2mo ago
No description
leowest
leowest2mo ago
aside from that it does look like it wrote it right in your DbContext u dont have any for modelbuilder right?
ApathyErr
ApathyErr2mo ago
modelbuilder?
ApathyErr
ApathyErr2mo ago
No description
ApathyErr
ApathyErr2mo ago
public partial class ProfitCalculatorDataBaseContext : DbContext
{
public ProfitCalculatorDataBaseContext()
{
}

public ProfitCalculatorDataBaseContext(DbContextOptions<ProfitCalculatorDataBaseContext> options)
: base(options)
{
}

public virtual DbSet<Order> Orders { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
=> optionsBuilder.UseSqlite("Data Source= E:\\VS Projects\\ProfitCalculator\\ProfitCalculator\\DataBase\\ProfitCalculatorDataBase.db");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Data).HasColumnName("data");
});

OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
public partial class ProfitCalculatorDataBaseContext : DbContext
{
public ProfitCalculatorDataBaseContext()
{
}

public ProfitCalculatorDataBaseContext(DbContextOptions<ProfitCalculatorDataBaseContext> options)
: base(options)
{
}

public virtual DbSet<Order> Orders { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
=> optionsBuilder.UseSqlite("Data Source= E:\\VS Projects\\ProfitCalculator\\ProfitCalculator\\DataBase\\ProfitCalculatorDataBase.db");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Data).HasColumnName("data");
});

OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
leowest
leowest2mo ago
mmm I wonder if that could be screwing it I dont really see anything wrong with your code aside from it what should happen is when you update, it will find if the db have an id already in it, grab it and whatever property u modify entityframework will track and update only those and when u create a new one if u dont define the Id, it should make the database handle it and auto increment an id for it but in your code for some reason its considering 0 as existent id so maybe delete the row with id 0 in your db other than that I am out of ideas here.
ApathyErr
ApathyErr2mo ago
No description
leowest
leowest2mo ago
u ahve some weirdly null rows
ApathyErr
ApathyErr2mo ago
these are the very records that I added. Then it turns out that the problem is already with displaying them in the program
leowest
leowest2mo ago
if its a test db I would nuke it and start fresh u shouldn't be allowing rows with null ids that shouldn't even be possible in first place
ApathyErr
ApathyErr2mo ago
I overwritten the database and reconnected it to the program
leowest
leowest2mo ago
ok did u remove all the bad rows from the table? or emptied it?
ApathyErr
ApathyErr2mo ago
I have banned an empty id. Do you think it's better to prohibit creating rows in which most of the columns are empty?
leowest
leowest2mo ago
no u can have empty columns u cannot have empty ids by the create table u have i.e.: INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT it shouldn't even happen in first place I guess for some finik reason the nulls were screwing new entries maybe so basically as long as ur column is properly create in the db it shouldn't happen
leowest
leowest2mo ago
leowest
leowest2mo ago
as you can see its just a infinite loop that if I hit y it adds a new entry when I hit n it exits and saves it
leowest
leowest2mo ago
No description
ApathyErr
ApathyErr2mo ago
As soon as I overwritten the database so that the id was not empty, the code started working. But because my program displayed records with Completed = 1, and I created records where Completed = 0, so I thought they were not being created
leowest
leowest2mo ago
I see glad its working then. its the id properly updating now too?
ApathyErr
ApathyErr2mo ago
yes
No description
leowest
leowest2mo ago
🙂
ApathyErr
ApathyErr2mo ago
thx again <3
leowest
leowest2mo ago
no worries u can also do this
public required string Url { get; set; }
public required string Url { get; set; }
if its a property that must be filled u append required to it and it will warn as error when u dont provide it
leowest
leowest2mo ago
No description