C
C#8mo 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
ApathyErrOP8mo 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
leowest8mo 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
ApathyErrOP8mo ago
✨ thx
leowest
leowest8mo ago
$close
MODiX
MODiX8mo ago
Use the /close command to mark a forum thread as answered
ApathyErr
ApathyErrOP8mo 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
leowest8mo 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
ApathyErrOP8mo 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
leowest8mo ago
is Num your Key? what is your entity like the class
ApathyErr
ApathyErrOP8mo ago
oId its key
leowest
leowest8mo ago
ah my bad I missed the oId
ApathyErr
ApathyErrOP8mo 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
leowest8mo ago
so u dont set the oId when u instatiate it right
ApathyErr
ApathyErrOP8mo ago
+
leowest
leowest8mo 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
ApathyErrOP8mo 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
leowest8mo ago
are u using sqlite or some other db engine
ApathyErr
ApathyErrOP8mo ago
sqlite
leowest
leowest8mo ago
do u have any tool to open ur sqlite? I wonder if its not updatingautoincrementing the key
ApathyErr
ApathyErrOP8mo 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
leowest8mo ago
No description
ApathyErr
ApathyErrOP8mo ago
db browser
leowest
leowest8mo 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
ApathyErrOP8mo ago
No description
leowest
leowest8mo ago
u dont need unique but u do need not null
leowest
leowest8mo ago
No description
leowest
leowest8mo ago
aside from that it does look like it wrote it right in your DbContext u dont have any for modelbuilder right?
ApathyErr
ApathyErrOP8mo ago
modelbuilder?
ApathyErr
ApathyErrOP8mo ago
No description
ApathyErr
ApathyErrOP8mo 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
leowest8mo 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
ApathyErrOP8mo ago
No description
leowest
leowest8mo ago
u ahve some weirdly null rows
ApathyErr
ApathyErrOP8mo 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
leowest8mo 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
ApathyErrOP8mo ago
I overwritten the database and reconnected it to the program
leowest
leowest8mo ago
ok did u remove all the bad rows from the table? or emptied it?
ApathyErr
ApathyErrOP8mo 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
leowest8mo 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
leowest8mo ago
leowest
leowest8mo 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
leowest8mo ago
No description
ApathyErr
ApathyErrOP8mo 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
leowest8mo ago
I see glad its working then. its the id properly updating now too?
ApathyErr
ApathyErrOP8mo ago
yes
No description
leowest
leowest8mo ago
🙂
ApathyErr
ApathyErrOP8mo ago
thx again <3
leowest
leowest8mo 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
leowest8mo ago
No description
Want results from more Discord servers?
Add your server