Entity Framework Miss Update - c#

Sometimes the entity is not updated within scope, but inserts are committed.
I'm thinking that this problem is due to the isolation level, added to the number of queries in the registry. I also think that it might be the order in which things are effective in the db, since the endpoint calls that imply changing the entity happen very quickly, even if in the correct order. I don't know...
The code is like:
using (var scope = new TransactionScope())
{
var db = new Context().Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;")
var student= db.Students.SingleOrDefault(x => x.ID == 1);
var schoolName = "TestSchool";
db.School.Insert(new School{ Name = schoolName }); // IT ALWAYS WORKS
student.School = schoolName; //SOMETIMES THIS CHANGE DOESN'T WORK
db.Save();
scope.Complete();
}
Any help?
It's only occur with mass data, making tests difficult

What you should do is query the school first, then assign the result to student.School
Something like this:
using (var scope = new TransactionScope())
{
var db = new Context().Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;")
var student= db.Students.SingleOrDefault(x => x.ID == 1);
var schoolName = "TestSchool";
db.School.Insert(new School{ Name = schoolName }); // IT ALWAYS WORKS
// Query new school here
var newSchool = db.School.SingleOrDefault(x => x.SchoolName = schoolName);
// Assign the result to student's School property
student.School = newSchool;
db.Save();
scope.Complete();
}
This way, Entity Framework would be able to "track" the changes and generate the correct SQL to update the database

Related

DbSet.Where() Returning No Records on Query Even When They Exist in Dataset

Okay, so I'm going crazy here. I've used DbSet.Where's 1000 times and for whatever reason it's not working in this particular xunit test. The issue seems to be rooted with my where statement trying to get a list of recipeid's = 1 so I can delete them. Whe I stop th ecode and look at my locals the params are set to 1 where designated, but the where won't pick it up.
I've consolidated the code a bit to make it more readable here, but it still doesn't work as is. What the heck am I missing?
[Fact]
public void DeleteIngredientListWithId_ReturnsProperCount()
{
//Arrange
var dbOptions = new DbContextOptionsBuilder<IngredientDbContext>()
.UseInMemoryDatabase(databaseName: $"IngredientDb{Guid.NewGuid()}")
.Options;
var sieveOptions = Options.Create(new SieveOptions());
var fakeIngredientOne = new Ingredient { RecipeId = 1 };
var fakeIngredientTwo = new Ingredient { RecipeId = 1 };
var fakeIngredientThree = new Ingredient { RecipeId = 2 };
//Act
using (var context = new IngredientDbContext(dbOptions))
{
context.Ingredients.AddRange(fakeIngredientOne, fakeIngredientTwo, fakeIngredientThree);
var service = new IngredientRepository(context, new SieveProcessor(sieveOptions));
var ingredients = context.Ingredients.Where(i => i.RecipeId == 1).ToList();
context.Ingredients.RemoveRange(ingredients);
context.SaveChanges();
//Assert
var ingredientList = context.Ingredients.ToList();
ingredientList.Should().ContainEquivalentOf(fakeIngredientThree);
ingredientList.Should().HaveCount(1);
context.Database.EnsureDeleted();
}
}
It looks like you might not be persisting the records you added to the database before you subsequently try to query (and then remove them). The Where method is looking at the database, which is empty until you SaveChanges()
Until you save the changes, the pending additions are probably waiting for you in context.Ingredients.Local

Entity Framework Core SQLite - Simulate Eager Loading in test

I have a repository that loads my entity (City) and its related data (PointsOfInterest)
public City GetCity(int cityId, bool includePointsOfInterest)
{
var city = _context.Cities.SingleOrDefault(x => x.Id == cityId);
if (includePointsOfInterest)
{
_context.Entry(city)
.Collection(x => x.PointsOfInterest)
.Load();
}
return city;
}
To test this method, I decided to go with SQLLite InMemory, as I could test the Eager load functionality.
Setup of the context:
SqliteConnection connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<CityInfoContext>()
.UseSqlite(connection)
.Options;
var context = new CityInfoContext(options);
var cities = new List<City>()
{
new City()
{
Id = 1,
Name = "New York City",
Description = "The one with that big park.",
PointsOfInterest = new List<PointOfInterest>()
{
new PointOfInterest()
{
Id = 1,
Name = "Central Park",
Description = "The most visited urban park in the United States."
},
new PointOfInterest()
{
Id = 2,
Name = "Empire State Building",
Description = "A 102-story skyscraper located in Midtown Manhattan."
}
}
}
}
context.Cities.AddRange(cities);
context.SaveChanges();
But looks like the SQLite always load its related data, which makes sense, since it is already in memory. But since it is supposed to simulate a Relational Database, is there a way to make it not load the related data automatically?
If not, how can I effectively test it? Should I go for in disk SQLite for my repository tests?
(I'm using EF in memory provider to test code that depends on the Repository)
Are you testing against the same instance of your context and the same DbSet collection you just inserted? If you are, the objects are there because you've just inserted them a step earlier, still in the graph.
Try querying your context like:
var c1 = context.Set<City>().AsQueryable().FirstOrDefault();
// assuming you have initialized the PointsOfInterest coll. in City.cs
Assert.Empty(c1.PointsOfInterest);
You can now apply the same access as _context.Set<City>().AsQueryable() in your repository.

Update Object without Select EF6 MySQL

Is it possible to update objects with Entity Framework, without grabbing them first?
Example: Here, I have a function that provides a Primary Key to locate the objects, pulls them, then updates them. I would like to eliminate having to pull the objects first, and simply run an UPDATE query. Removing the need for the SELECT query being generated.
public async Task<int> UpdateChecks(long? acctId, string payorname, string checkaccountnumber, string checkroutingnumber, string checkaccounttype)
{
using (var max = new Max(_max.ConnectionString))
{
var payments = await
max.payments.Where(
w =>
w.maindatabaseid == acctId && (w.paymentstatus == "PENDING" || w.paymentstatus == "HOLD")).ToListAsync();
payments.AsParallel().ForAll(payment =>
{
payment.payorname = payorname;
payment.checkaccountnumber = checkaccountnumber;
payment.checkroutingnumber = checkroutingnumber;
payment.checkaccounttype = checkaccounttype;
payment.paymentmethod = "CHECK";
payment.paymentstatus = "HOLD";
});
await max.SaveChangesAsync();
return payments.Count;
}
}
You can use the Attach() command to attach an entity you already know exists and then call SaveChanges() will will call the appropriate update method. Here is some sample code from the MSDN article on the topic:
on the subject:
var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };
using (var context = new BloggingContext())
{
context.Entry(existingBlog).State = EntityState.Unchanged;
// Do some more work...
context.SaveChanges();
}
Note that this is general EF logic, not related to any specific database implementation.

Can Entity Framework add many related entities with single SaveChanges()?

I am writing many (20+) parent child datasets to the database, and EF is requiring me to savechanges between each set, without which it complains about not being able to figure out the primary key. Can the data be flushed to the SQL Server so that EF can get the primary keys back from the identities, with the SaveChanges being sent at the end of writing all of the changes?
foreach (var itemCount in itemCounts)
{
var addItemTracking = new ItemTracking
{
availabilityStatusID = availabilityStatusId,
itemBatchId = itemCount.ItemBatchId,
locationID = locationId,
serialNumber = serialNumber,
trackingQuantityOnHand = itemCount.CycleQuantity
};
_context.ItemTrackings.Add(addItemTracking);
_context.SaveChanges();
var addInventoryTransaction = new InventoryTransaction
{
activityHistoryID = newInventoryTransaction.activityHistoryID,
itemTrackingID = addItemTracking.ItemTrackingID,
personID = newInventoryTransaction.personID,
usageTransactionTypeId = newInventoryTransaction.usageTransactionTypeId,
transactionDate = newInventoryTransaction.transactionDate,
usageQuantity = usageMultiplier * itemCount.CycleQuantity
};
_context.InventoryTransactions.Add(addInventoryTransaction);
_context.SaveChanges();
}
I would like to do my SaveChanges just once at the end of the big loop.
You don`t need to save changes every time if you use objects refernces to newly created objects not IDs:
var addItemTracking = new ItemTracking
{
...
}
_context.ItemTrackings.Add(addItemTracking);
var addInventoryTransaction = new InventoryTransaction
{
itemTracking = addItemTracking,
...
};
_context.InventoryTransactions.Add(addInventoryTransaction);
...
_context.SaveChanges();
Since they're all new items rather than
itemTrackingID = addItemTracking.ItemTrackingID,
you could go with
addItemTracking.InventoryTransaction = addInventoryTransaction;
(or whatever the associated navigation property is) and pull the _context.SaveChanges() out of the loop entirely. Entity Framework is very good at inserting object graphs when everything is new. When saving object graphs containing both new and existing items setting the associated id is always safer.
How about:
var trackingItems = itemCounts
.Select(i => new ItemTracking
{
availabilityStatusID = availabilityStatusId,
itemBatchId = i.ItemBatchId,
locationID = locationId,
serialNumber = serialNumber,
trackingQuantityOnHand = i.CycleQuantity
});
_context.ItemTrackings.AddRange(trackingItems);
_context.SaveChanges();
var inventoryTransactions = trackingItems
.Select(t => new InventoryTransaction
{
activityHistoryID = newInventoryTransaction.activityHistoryID,
itemTrackingID = t.ItemTrackingID,
personID = newInventoryTransaction.personID,
usageTransactionTypeId = newInventoryTransaction.usageTransactionTypeId,
transactionDate = newInventoryTransaction.transactionDate,
usageQuantity = usageMultiplier * t.trackingQuantityOnHand
});
_context.InventoryTransactions.AddRange(inventoryTransactions);
_context.SaveChanges();
However I haven't worked with EF for quite a while and above code is written in notepad so I cannot vouch for it

Why is a validation exception thrown on a field which is not being updated?

I am using EF 6.0.2 and trying to update only the Status field of an entity.
var drama = new Drama { Id = id };
using (var ctx = new DataContext()) {
ctx.Dramas.Attach(drama);
drama.Status = state;
ctx.SaveChanges();
}
This throws a ValidationException: The ClassName field is required.
The entity already exists, and is valid (including having a ClassName). Id is the entity key.
What's going on here to cause the exception to be thrown?
You're saying there already is an entity with the given Id in the database and you'd only like to change its Status value?
That's not what you're doing in your code. You have created a new entity with the given Id and set only its Status value. That's why it's throwing a ValidationException: ClassName field is empty unless you're setting it in Drama constructor.
To modify an existing entity you should first retrieve it from the database, then modify it and save the changes:
using (var ctx = new DataContext()) {
var drama = ctx.Dramas.Single(d => d.Id == id);
drama.Status = state;
ctx.SaveChanges();
}
EDIT:
If you want to simulate a scenario of editing a detached entity, you still need its values to be valid. Try fulfilling all the validation requirements before attaching the entity (i.e. fill in the ClassName), then Attach it, update Status and SaveChanges:
var drama = new Drama { Id = id, ClassName = "Dummy" };
using (var ctx = new DataContext()) {
ctx.Dramas.Attach(drama);
drama.Status = state;
ctx.SaveChanges();
}
When you do edits in EF, you should get the entire record that you are editing and then put the fields whatever you want to update.
using (var ctx = new DataContext()) {
drama = ctx.Dramas.Where(O => O.Id = id);
drama.Status = state;
ctx.Dramas.Attach(drama);
ctx.SaveChanges();
}
Hope this helps

Categories