Marking navigation property as modified in Entity Framework 7 - entity-framework-core

I have an EF7 DbContext with disabled change tracking because I want to mark all changes explicitly:
var entry = context.Entry(changedEntity);
entry.Property(propertyName).IsModified = true;
This works exactly as I want it to.
However, this does not work when a reference (navigation property) has been updated.
For example, let's say my entity has two properties - ParentId and Parent where ParentId is a foreign key and Parent is the reference to the parent entity.
Calling
entry.Property("Parent").IsModified = true;
does not work and throws ModelItemNotFoundException because Parent is not a property of the entity in terms of EF (it is a navigation instead).
In EF6, this could be done as follows:
var reference = context.Entry(changedEntity).Reference("Parent");
reference.CurrentValue = reference.CurrentValue;
IN EF7, there is no such function. I can get to the INavigation object with
entry.Metadata.GetNavigation("Parent")
but cannot see any way to mark it as modified.
So, how should I do it?
Note:
I know that setting ParentId would work, but this is not suitable for me because the referenced entity does not have ID yet as it has just been created and will get its ID from database when saved. Thus, I need to set it through the reference Parent.
Edit:
The note above was true for EF6 but is no longer valid for EF7 which I was not aware of. Thus, the solution is just as described in the note and answer below.

Wow, it seems that when a new entity is attached to the DbContext, it actually gets ID (-1 in my case). So, I can set ParentId even when the target entity is new and has not been added to the database yet.
I wonder whether there are any checks that the new ID is unique (there could already be an entry with ID -1 in database).

Related

Why does DbSet.Add change properties of other entities?

I have a rare case where the call of DbSet<T>.Add() changes some properties of other entities that are already in the DbSet<T>. Unfortunately, it happens very rarely, and the only evidence I have are some log files, so I have not yet been able to reproduce it locally.
The behavior is like this:
First, we load some entities from the DbSet using a LINQ query.
Then, some of these entities are changed. No SaveChanges() yet.
Now we add some entities by calling DbSet<T>.Add().
Some of the entities of step 2 are changed in step 3 (one foreign-key property of them is set to null).
Any idea? Is that something that can happen on a EF 6 Code-First model?
The only possibility I can think of is that the DbContext refreshes some data from the database, but we don't want it to do that at this point.
EDIT: The code is currently scattered with log statements, since we have been chasing this bug since weeks. These are the relevant code sections:
// parameter: List<Entry> entriesFromUser
var entriesFromDb = db.Entries
.Where(...)
.OrderBy(...)
.ToList();
var newEntries = MergeEntries(entriesFromDb, entriesFromUser);
var propertyBefore = entriesFromDb[0].MyForeignKeyId;
for (var i = 0; i < newEntries.Count; i++)
{
// make sure that the "new entry" is not a modified one
if (entriesFromDb.Contains(newEntries[i])
{
throw new Exception();
}
db.Entries.Add(newEntries[i]);
}
var propertyAfter = entriesFromDb[0].MyForeignKeyId;
Debug.Assert(propertyBefore == propertyAfter); // <=== fails sometimes
db.SaveChanges();
Please note that the changed foreign key is NOT on the entity being added to the DbSet. It's on an entity that comes from the database, but has been changed in the same transaction.
D'oh. Found the reason. Hope it helps someone else.
We are using Foreign Key Associations, which means that we have both the navigation property entry.MyForeignKey and the Foreign Key property entry.MyForeignKeyId, which has many advantages, but it also means you have to be careful when using sometimes this, sometimes that property.
Turns out we had the following assignment somewhere deep in the code, where all the data of one entry is copied to another one:
entry.MyForeignKeyId = otherEntry.MyForeignKeyId
entry.MyForeignKey = otherEntry.MyForeignKey
However, in many scenarios, you set a foreign key value to an entity's MyForeignKeyId but leave the property MyForeignKey null, because the parent entity is not loaded. This is fine as long as you don't assign null to the entity's MyForeignKey property, because it seems that EF would then set MyForeignKeyId to null too.
So it seems that after our code assigned null to MyForeignKey, the entity lingered in memory with a null MyForeignKey and a non-null MyForeignKeyId. As soon as the next DbSet command was executed (the Add() operation), the DbSet noticed that MyForeignKey has received a null assignment, so DbSet went on and assigned null to MyForeignKeyId too.

Entity Framework / EF4: Multiple inserts of related entities in a transactionscope

I have a similar problem.
I want to make two inserts in the same transactionscope. The objects are related and have a FK relationship between them, but for several reasons I do not want to connect them via the navigation property, but only by ID.
This is a simplification of what I what I want to accomplish:
Order o = new Order();
OrderDetails d = new OrderDetails();
new Repository().SaveNew(o, d);
class Repository{
void SaveNew(Order o, OrderDetails d){
using (TransactionScope transaction = new TransactionScope())
{
_context.Connection.Open();
// order
_context.Orders.ApplyChanges(o);
_context.SaveChanges();
// details
d.OrderID = o.ID;
_context.OrderDetails.ApplyChanges(d);
_context.SaveChanges(); <--- UpdateException
_context.Connection.Close();
transaction.Complete();
}
}
}
The problem is that I get an UpdateException because the FK evaluation fails. I tried to remove the FK relationship and running the exact same piece of code, and it worked fine, and both objects had the right properties set. So why does this approach fail? And how should this instead be done? Again, I do not want to attach the entites via their navigation properties.
Thank you!
I would leave the FK relationship in the database, but delete the AssociationSet and Association from the SSDL. The designer won't let you do this, you have to edit the XML manually.
I am using EF 4 btw.
Then use AddObject and SaveChanges in your SaveNew method to add the first (parent) object. Set the foreign key Property on the child and add it with AddObject and SaveChanges.
I do not have development environment running to test this, but what I think is happening is:
Assuming that the id is generated in the database. At the point when you save the order you do not know the ID.
Then the order ID of the order detail is set to the ID of the order, but the order was not reloaded from the database. I suspect that the value is 0.
When you try to save the order detail with FK of 0, you get an error.
Either save both at the same time so that EF does the work for you, or reload the order.

Entity Framework, changing EntityKey leaves Entity as "UnChanged"

I have an entity with a status property that I would like to update.
I would like to do the following:
const int NEW_STATUS = 2;
myEntity.StatusReference.EntityKey = new EntityKey("SetName", "KeyName", NEW_STATUS);
When this is passed to the context, its state is "UnChanged", despite me changing the relationship! This means the save will not be persisted.
The entity comming in is from a different context to the one that its being attached to and saved.
Anyone know how I can update just the entitykey and persist it!?
Thanks in advance,
David
You can't. EntityKeys are designed to be mapped to primary keys, which, in any good DB design, will never change. If you've mapped your EntityKey to something which is not a PK, change it to the PK. If your DB design calls for PKs to change, please reconsider that design. (Removed after you changed the question.)
Added, upon re-reading the question: Are you actually wanting to update the EntityKey of the entity, or do you just want to change the status property? If the latter, try one of the following:
entity.Status = someStatusInstance;
...or...
entity.StatusReference.EntityKey = myEntity.EntityKey = new EntityKey("SetName", "KeyName", NEW_STATUS);
If your entity state isn't modified, you probably have the order of operations wrong when adding to/saving the context. You would need to show that when asking for help on it.

Entity Framework won't SaveChanges on new entity with two-level relationship

I'm building an ASP.NET MVC site using the ADO.NET Entity Framework.
I have an entity model that includes these entities, associated by foreign keys:
Report(ID, Date, Heading, Report_Type_ID, etc.)
SubReport(ID, ReportText, etc.) - one-to-one relationship with Report.
ReportSource(ID, Name, Description) - one-to-many relationship with Sub_Report.
ReportSourceType(ID, Name, Description) - one-to-many relationship with ReportSource.
Contact (ID, Name, Address, etc.) - one-to-one relationship with Report_Source.
There is a Create.aspx page for each type of SubReport. The post event method returns a new Sub_Report entity.
Before, in my post method, I followed this process:
Set the properties for a new Report entity from the page's fields.
Set the SubReport entity's specific properties from the page's fields.
Set the SubReport entity's Report to the new Report entity created in 1.
Given an ID provided by the page, look up the ReportSource and set the Sub_Report entity's ReportSource to the found entity.
SaveChanges.
This workflow succeeded just fine for a couple of weeks. Then last week something changed and it doesn't work any more. Now instead of the save operation, I get this Exception:
UpdateException: "Entities in 'DIR2_5Entities.ReportSourceSet'
participate in the 'FK_ReportSources_ReportSourceTypes' relationship.
0 related 'ReportSourceTypes' were found. 1 'Report_Source_Types' is expected."
The debug visualizer shows the following:
The SubReport's ReportSource is set and loaded, and all of its properties are correct.
The Report_Source has a valid ReportSourceType entity attached.
In SQL Profiler the prepared SQL statement looks OK. Can anybody point me to what obvious thing I'm missing?
TIA
Notes:
The Report and SubReport are always new entities in this case.
The Report entity contains properties common to many types of reports and is used for generic queries. SubReports are specific reports with extra parameters varying by type. There is actually a different entity set for each type of SubReport, but this question applies to all of them, so I use SubReport as a simplified example.
I realise I'm late to this, but I had a similar problem and I hacked through it for about 3 hours before I came up with a solution. I'd post code, but it's at home - I can do it later if someone needs it.
Here are some things to check:
Set a breakpoint on the SaveChanges() call and examine the object context in depth. You should see a list of additions and changes to the context. When I first looked, I found that it was trying to add all my related objects rather than just point to them. In your case, the context might be trying to add a new Report_Source_Type.
Related to the previous point, but if you're retrieving the report source, make sure it is being retrieved from the database by its entity key and properly attached to the context. If not, your context might believe it to be a new item and therefore its required relationships won't be set.
From memory, I retrieved my references using the context.GetObjectByKey method, and then explicitly attached those objects to the context using the context.Attach method before assigning them to the properties of my original object.
I got this error because the table didn't have a primary key, it had a FK reference, but no PK.
After adding a PK and updating the model all is well.
Check if your ReportSource was loaded with the NoTracking option or if its EntityState == 'Detached'. If so, that is your problem, it must be loaded in the context.
This tends to happen if your database tables have a 1 - 1 relationship with each other. In your example reportsourceset expects a reportsorttypes with whatever id it is referencing. I have run into this problem when my relationship is linking two primary keys from opposite tables together.
I've got the same error because of new object instance which created "behind the scene" in "Added" state. This was not obvious.
I got this error when I added the new entity to the context but forgot to add the new entity to its parent's collection in the object graph.
For example:
Pet pet = new Pet();
context.Pets.Add(pet);
// forgot this: petOwner.Pets.Add(pet);

Entity Framework: Model doesn't reflect DB

I'm probably thinking about this all wrong but I have the following db tables:
When I run the EF Wizard in VS2008 I get the following model:
You'll notice that in the EF model shows that the Entity has no field for EntityTypeID or EntityStatusId. Instead it shows it as a navigation property, so the field appears to not be addressable when I instantiate an Entity (pardon the terminology confusion: Entity is a Table/Class in my name space not in the EF namespace). How can I assign an EntityTypeID and StatusTypeID when instantiating an Entity?
Yes, the entity framework hides foreign key ID properties and shows navigation properties instead. There is a lengthy discussion about why it does that, here. The usual means of assigning a reference to another entity is to assign the entity instance, rather than the foreign key ID value, like this:
var foo = new Entity();
var status = (from .... select ...).FirstOrDefault();
foo.StatusCodes = status;
However, it is possible to assign a foreign key ID directly, if you happen to know what it is:
foo.StatusCodesReference = new EntityKey(
"MyEntityContextName.StatusCodesEntitySetName", "StatusCodeId", value);
Obviously, substitute the real values in the above.