If I have a Parent object which contains foreign key references to the Child table and I add a Child to the Parent do I need to call Context.Add() on both the child and the parent separately? or just the parent?
given that:
Parent.childobj=child;//foreign key reference set to the child object
This:
mycontext.Add(Child);
mycontext.Add(Parent);
or
mycontext.Add(Parent);
If both entities already exist and you want to relate the child with the parent, and also the parent entity is been tracked by the context, updating the FK property is enough.
Parent.ChildId=child.Id;
context.SaveChanges();
Now if Child is a new entity and parent already exist and has been tracked by the context, then use the reference property to associate both:
Parent.childobj=child; // You can also do this if both exist already in your DB
context.SaveChanges();
If both are new then add the parent to the context, that will persist also the related child:
Parent.childobj=child;
context.Parent.Add(parent);
context.SaveChanges();
Related
I'm using EF Core 5.0.11. My models looks like:
Entity_A:
Id
List<Entity_B>
Entity_B:
Id
Entity_A
<shadow>Entity_A_Id
when I'm trying to set in code:
var a = new Entity_A();
dbContext.Add(a);
dbContext.SaveChanges()
...
var b = new Entity_B();
b.Entity_A = a;
I get this Entity changed to Detached state due to severed relationships to its parent entity
It only works if I remove a list from Entity_A and update to just .WithMany():
Entity_A:
Id
Entity_B:
Id
Entity_A
<shadow>Entity_A_Id
Is it an intended behavior that makes me change one-to-many relationships in a way so that they should be always initiated from parent entity only unless no collection of child entities exists on parent?
If I add child to parent collection it works just fine. Getting rid of shadow FK property doesn't help either.
I have the following issue when trying to save a brand new object tree.
I have Created an object with a number of child objects. The child objects are all 1 level deep from the initial object created. My problem is that one of the child objects that I am attempting to create also has a FK into one of the other child objects. So on the initial creation of these objects the FK's are of course 0 because the child object that hasn't yet been created has it's PK currently at 0. When I call SaveChanges on the context it errors because the key's are indeterminate on the child object that is reliant on the existence of the other child object. This is quite a large object tree and so it seems I will need to save the parent first and then other objects in order so that I can obtain the new PK value to use against those tables that are reliant on others. The trouble is I want an all or nothing situation, so I want all objects to save or none. SaveChanges in EF 6 removed the ability to pass false as a parameter and then call SaveAllChanges(). What's the best approach for me now to get this to work?
You should use transaction. In transaction, you should first add parent object to dbset and use Context.SaveChanges() the entity will not be created on db until you commit the transaction. However it will reserve id(primary key). So you can use this id on child objects. You can do the same thing for child objects, if you need id(primary key) use Context.SaveChanges().
using (var myTransaction = Context.Database.BeginTransaction())
{
try
{
//Crate Parent Object
Context.SaveChanges();
//Create Child Object;
Context.SaveChanges();
//Other Childs
Context.SaveChanges();
//If everything goes well
myTransaction.Commit();
}
catch (Exception)
{
myTransaction.Rollback();
}
}
Using Salesforece API via .Net (C#) I try to implement a Parent - child Relation between a custom object.
Whichever is going to be detail object create a master detail field which would point to the other object. this would achieve the relationship. I want to Create a Parent as well as Child custom object at a same time ? is there any way to create a parent - child relationship between a custom object via foreign keys?
When given Object reference to its parent Object Salesforce give error status:
More than 1 field provided in an external foreign key reference in entity: ChidObj__c
I have an intermittent problem in a production system that I haven't been able to recreate locally. What appears to be happening is that for no obvious reason during an edit of a child entity and saving the parent containing the collection the parent association on the child entity is removed in the database. Effectively orphaning the child entity.
Here is the fluent mapping:
mapping.HasMany<ExpenseItem>(x => x.ExpenseItems).Cascade.AllDeleteOrphan();
The entity can also be directly saved (it is also aggregate root), but during testing this has not be shown to remove the parent association.
There are no references to the parent itself in the child object the association is all in the DB handled by Nhibernate.
There is also no possibility of assigning the same child entity to another parent as expense item (child entity) cannot be added outside of its parent directly. See code below.
public virtual ExpenseItem AddNewExpenseItem(ExpenseAnalysis analysis,
string recipientName,
string purchaseAccountReference,
string expenseDescription,
string expenseNotes,
Money value,
VATAnalysis vat)
{
Validate.IsNotNull<ExpenseAnalysis>(analysis);
Validate.IsNotNull(expenseDescription);
....
ExpenseItem newExpenseItem = new ExpenseItem(analysis,
recipientName,
purchaseAccountReference,
expenseDescription,
expenseNotes,
value,
vat,
expenseItemUniqueReference,
true,
Candidate.Assessment);
_expenseItems.Add(newExpenseItem);
....
Any ideas?
It would definitely help to see your mapping but take a look at
I'd also map the ExpenseItem with a reference to its parent
How to delete child object in NHibernate?
basically you ve to set inverse on the relationship so that NHibernate does not try to update the deleted record with a null victim. And you set Cascade.All | Cascade.DeleteOrphans so that we aren't just breaking the relationship by nulling out the victim, but deleting the entire child record.
This problem was caused by a bug in NHibernate. I had set the session to flush never however when you call isdirty on the session the session was being flushed first. The user was deleting the expense item then cancelling the edit but during the isdirty check the deletion was being flushed. Managed to work around this by changing how the session was being managed for this type of dialog.
I have a object structure like this:
public class Entity
{
IList<Relationship> Relationships{get;set;}
}
public class Relationship
{
public Relationship(Entity parent, IList<Entity> children)
{
//set properties
}
Entity Parent{get;private set;}
IList<Entity> Children{get;private set;}
}
The Relationship contains all information about the parent and child instances, and I would like to share the same Relationship instance on the parent and all child instances that make up the relationship.
Now when I come to load my entities from the db I start with the top entity, which then loads the relationships. I thought I could just cache the relationship I am building and reuse the same instance for the children. But this doesn't work as to create a relationship I need to load all child entities, so each child entity tries to recreate the same relationship I am currently trying to get the children for before it has been created, so I end up creating all of the relationship instances below me in the tree before I can add the relationship to the cache.
Is there a way I can get round this without making the children a settable property of my relationship, so I can create the reference to the relationship before the children are created?
So I managed this by introducing a RelationshipBuilder class which I used to keep track of the parents and children of a relationship without actually creating it.
This enabled me to load an entity and create its relationships in the builder, when the relationships tried to create the children they checked with the builder to see that the relationship was already being created and returned.
This meant I could navigate all the way down the hierarchy loading all of the entity instance and setting the parent entity and child entities associated with the relationships. Once all of the entities had been loaded and the recursion had completed and we were returned to the entry point where we started loading the entities I ask the relationship builder to resolve all the relationships. This then creates each relationship it has been informed about and sets the relationship instance on the parent and child instances which are involved in that relationship.