Update a record in Entity Framework Core - c#

I have an existing record from database that I have retrieved using Entity Framework:
MyDataObject myExistingObject= _dbContext.data
.Where(s => s.Id == myId).FirstOrDefaultAsync();
Externally, I have received another MyDataObject newDataObjectForSameRow that contains updated information for myExistingObject - all fields except Primary Key, that is initially set to 0 in the newDataObjectForSameRow.
How can I instruct Entity Framework "replace the row that has currently myExistingObject by newDataObjectForSameRow, however keeping the same Primary Key"?

Try to use below code:
newDataObjectForSameRow.Id = myId;
MyDataObject myExistingObject = _dbContext.data.Where(s => s.Id == myId).FirstOrDefaultAsync();
_dbContext.Entry(myExistingObject).CurrentValues.SetValues(newDataObjectForSameRow);
_dbContext.SaveChanges();

Related

What is a good way to archive data with the identity column using EF Core?

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 hour ago.
Improve this question
I'm using .NET 6 and EF Core 6.0.13. I have two databases Foo and FooArchive with identical schemas. I need to archive (migrate) data that are older than a year from Foo to FooArchive for 7 tables. What's the best way to do this with EF Core? I will describe below what I tried and the issues I'm running into.
NOTE: There are no foreign keys or any relationships defined for any table in both DBs and so no navigation properties, etc.
There are FooContext and FooArchiveContext classes both using the same entity models but different connections and injected into the repository class
Query for the customer ids whose account is older than 365 days on a different transaction
var customerIds = GetCustomerIds();
Loop through CustomerIds collection and archive one customer at a time
foreach(var customerId in customerIds)
{
using(var fooTx = _fooContext.Database.BeginTransaction())
using(var fooArchiveTx = _fooArchiveContext.Database.BeginTransaction())
{
//Series of left joins to get the data from 7 tables
var recordsToArchive = (from cust in _fooContext.Customers
join ord in _fooContext.Orders on ord.CustId equals cust.Id into co
from ord in co.DefaultIfEmpty()
join odt in _fooContext.OrderDetails on odt.OrderId equals ord.id into ordt
.
where cust.id = customerId
select new {
Customer = cust,
Order = ord,
OrderDetail = odt,
.
.
}).ToList();
var customer = recordsToArchive.Select(x => x.Customer).Distinct().First();
var orders = recordsToArchive.Select(x => x.Order).Where(x != null).Distinct();
var orderDetails = recordsToArchive.Select(x => x.OrderDetail).Where(x != null).Distinct();
.
.
// Check if the record to be migrated is already in FooArchiveContext
var existingRecord = _fooArchiveContext.Customers.FirstOrDefault(x => x.Id == customerId);
if(existingRecord == null)
{
_fooArchiveContext.Customers.Add(customer);
_fooArchiveContext.Orders.AddRange(orders);
_fooArchiveContext.OrderDetails.AddRange(orderDetails);
.
}
else
{
_fooArchiveContext.Customers.Update(customer);
_fooArchiveContext.Orders.UpdateRange(orders);
_fooArchiveContext.OrderDetails.UpdateRange(orderDetails);
.
}
_fooArchiveContext.SaveChanges();
//Remove the record from fooContext
_fooContext.OrderDetails.RemoveRange(orderDetails);
_fooContext.Orders.RemoveRange(orders);
_fooContext.Customers.Remove(customer);
.
_fooContext.SaveChanges();
fooArchiveTx.Commit();
fooTx.Commit();
}
}
Is what I'm doing the right approach? I think I may have to use the AutoMapper to copy entities in between two contexts. It works in the InMemory database but fails when I try it against the actual SQL Server instances. I get an error
Cannot insert explicit value for identity column in table 'Orders' when IDENTITY_INSERT is set to OFF
I would like to keep the same Ids as in the original db instance (fooContext).
I guess I can remove the Id in the entity object and save. Then query for the new Id and update the related entities but sounds tackier than the code I already have. I've seen SO answers where EF core is turning identity insert option on and off before and after calling SaveChanges() like below but haven't tried.
db.Users.Add(user);
db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT MyDB.Users ON");
db.SaveChanges();
db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT MyDB.Users OFF");
transaction.Commit();
Thanks for your help.
If I understand your problem correctly
Your approach of looping through each customer and archiving their records one at a time seems reasonable. However, there are a few areas where you can improve your implementation.
Firstly, you should avoid querying the database multiple times for the same data. In your code, you are querying the same data multiple times to get the customers, orders, and order details. This can be improved by using the Include method to eagerly load the related entities along with the primary entity.
Secondly, you should avoid duplicating code. In your code, you have duplicate code for adding and updating the entities in the archive database. You can reduce the duplication by using the Attach method to attach the entities to the context and then calling Update or Add depending on whether the entity is already in the context or not.
Thirdly, you should use a bulk insert/update operation instead of adding/updating the entities one at a time. EF Core does not have built-in support for bulk operations, but you can use third-party libraries like Entity Framework Extensions or Z.EntityFramework.Plus to perform bulk operations.
Finally, you should avoid setting the identity column values explicitly. Instead, let the database generate the identity values for you. To do this, you can remove the identity column from your entity models or use the ValueGeneratedOnAdd() method in your entity configuration.
With these improvements in mind, here's an example implementation of your code:
using (var fooTx = _fooContext.Database.BeginTransaction())
using (var fooArchiveTx = _fooArchiveContext.Database.BeginTransaction())
{
var cutoffDate = DateTime.UtcNow.AddYears(-1);
var customerIds = _fooContext.Customers
.Where(c => c.CreatedAt < cutoffDate)
.Select(c => c.Id)
.ToList();
foreach (var customerId in customerIds)
{
var customer = _fooContext.Customers
.Include(c => c.Orders)
.ThenInclude(o => o.OrderDetails)
.FirstOrDefault(c => c.Id == customerId);
if (customer != null)
{
if (_fooArchiveContext.Customers.Any(c => c.Id == customerId))
{
_fooArchiveContext.Attach(customer);
_fooArchiveContext.Update(customer);
}
else
{
_fooArchiveContext.Add(customer);
}
_fooArchiveContext.SaveChanges();
_fooArchiveContext.Orders.BulkInsert(customer.Orders);
_fooArchiveContext.OrderDetails.BulkInsert(customer.Orders.SelectMany(o => o.OrderDetails));
_fooContext.OrderDetails.RemoveRange(customer.Orders.SelectMany(o => o.OrderDetails));
_fooContext.Orders.RemoveRange(customer.Orders);
_fooContext.Customers.Remove(customer);
_fooContext.SaveChanges();
}
}
fooArchiveTx.Commit();
fooTx.Commit();
}
In this code, we first get the list of customer IDs whose accounts are older than a year. We then loop through each customer and retrieve their orders and order details using the Include method. We then check if the customer already exists in the archive database and use the Attach and Update methods to update the existing customer, or the Add method to add a new customer.
We then use the BulkInsert method from the Entity Framework Extensions library to insert the orders and order details in bulk. We also remove the orders, order details, and customer from the source database using the RemoveRange method.
Finally, we call SaveChanges on the archive and source contexts and commit the transactions.

Fetching multiple levels of related records in Entity Framework .NET5

I have the following code. It brings back the Show and its related Slides. However Slide also has related Items but I have no idea how to make the query include those (There is a foreign key in the db).
Show sh = (from s in _context.Shows
where s.ShowId == id
select new Show()
{
ShowId=s.ShowId,
ShowName=s.ShowName,
Slides=s.Slides
}).FirstOrDefault();
How do I modify this to make it also fetch the list of Items for each Slide?
I am using .Net5
If you defined your DbContext correctly the LINQ would be
Show sh = _context.Shows
.Where(s => s.ShowId == id)
.Include(s => s.Slides)
.ThenInclude(sl => sl.Items)
.FirstOrDefault();

How to select specific fields to update in EF

I want to get all records from a database with #where, then update them. To do this, I have created a query like this:
public async Task MarkAllAsActive()
{
var currentUserId = _userManager.GetCurrentUserId();
await _workOrders.Where(row => row.Status == WorkOrderStatus.Draft).ForEachAsync(row =>
{
row.Status = WorkOrderStatus.Active;
_uow.MarkAsChanged(row, currentUserId);
});
}
But this query selects all fields from the database which isn't good. To solve this I try to select just specific fields like ID, Status:
public async Task MarkAllAsActive()
{
var currentUserId = _userManager.GetCurrentUserId();
await _workOrders.Select(row=>new WorkOrder { Id=row.Id,Status=row.Status}).Where(row => row.Status == WorkOrderStatus.Draft).ForEachAsync(row =>
{
row.Status = WorkOrderStatus.Active;
_uow.MarkAsChanged(row, currentUserId);
});
}
But it return this error:
The entity or complex type 'DataLayer.Context.WorkOrder' cannot be constructed in a LINQ to Entities query.
I've seen a similar post and the same error, but my problem is different because I want to update.
How can I do this?
Sadly you have to fetch the entire entity.
In order to update an entity with EF, the class type edited has to be a DbContext mapped entity .
If you want to Update without fetching Entities to the server , and without writing any SQL you can use Entity Framework Extended Library .
See the update section on the site.
Fetching entity within same entity will not work in your case, as you are getting only selected columns. e.g. You are fetching WorkOrder entity in WorkOrder again.
I would suggest you to use DTO to load selected columns only. It should work. But at the time of update you will have to copy same to db object.

Remove a record in entity framework

I'm working with entity framework for sometimes now and one thing that really irritates me is the fact that to delete an item we have to find the object and then remove it. so if we have the PK of the record we have to get the object and then remove the object.
ex:
Category category = db.Categories.Find(categoryId);
db.Categories.Remove(category);
db.SaveChages();
In this method we are hitting database twice..!!!
is there a way to remove the record with just hitting the database once?
For those none-believers this is the glimpse out come: :)
// no trip to database
var rec = db.TableName.Local.SingleOrDefault(r => r.Id == primaryKey);
if (rec == null) throw NotFoundOrWhateverException();
// still no trip to database, if I remember right
db.TableName.Remove(rec);
// trip to database
db.SaveChanges();
IF you don't want to get the complete object you can try this way using the primary key property of it:
Category category = new Category () { Id = categoryId } ;
db.Categories.Attach(category);
db.DeleteObject(category);
db.Savechanges();
If you are using EF 5 then you can use EntityFramework.Extended Library using NUGETand can do like this:
db.Categories.Delete(c => c.Id == categoryId);
[Answer turned out to be incorrect. Removed content to keep from confusing others. Kept the post for comment thread.]

How to update related entries of different tables when using Entity Framework 4.0?

Is there any shorter way to do this update?
void Update(Table1 table1Entry, Table2[] table2entries)
{
entities.Table1.Attach(table1Entry);
var table2EntriesIds = table2entries.Select(a => a.Id);
var updates = entities.Table2
.Where(a => table2EntriesIds.Contains(a.Id));
foreach(var update in updates)
{
entities.Table2.Attach(update);
}
var deletions = entities.Table2
.Where(a => a.Table1Id == table1Entry.Id);
.Where(a => !table2EntriesIds.Contains(a.Id));
foreach(var deletion in deletions)
{
entities.DeleteObject(deletion);
}
var insertions = table2entries.Except(matches);
foreach(var insertion in insertions)
{
entities.AddToTable2(insertion);
}
entities.SaveChanges();
}
where Table2 has an Table1_Id foreign key.
The idea is correct. You can optimize it so for example you will not load separately relations to update and relations to delete but you will still have to manually synchronize current detached state of your entities with state in the database. The only way to synchronize the state of the entity graph is to do it manually per entity and relation.
The question is if your code works. I think it doesn't. It doesn't update any records because it doesn't change state of the records to modified. You also cannot attach again record loaded from the context. As the last point if those table1 and table2 are somehow related I don't see any code working with the relation itself (unless you use FK properties).

Categories

Resources