ENTITY FRAMEWORK CORE 1.1
I just want to demonstrate my question, here it is.
I have two class. Let's say.
Class Owner has these properties:
public class Id {get;set;}
public class Name {get;set;}
public class ICollection<Car> Cars {get;set;}
Class Car, with these properties:
public class Id {get;set;}
public class Name {get;set;}
public class Owner Owner {get;set;}
so, owner has many cars. and car belongs to specific owner.
now, when i generate it on entity framework Car Class
will have foreign key of OwnerId.
Now my question is, I have dropdown for Owners.
And I want to add a car and choose their owner.
When i add a car and Owner(what i need is Id only in UI).
I have Car's Id, Name, and also OwnerId.
In saving/inserting, it works fine. But when i update/edit the Car and change its Parent(i mean Id which is Foreign key OwnerId),
the Car's Properties(like name) were the only thing has changed and not his ParentId(OwnerId).?
How to move Child to different Parent.
My idea was to remove the child from its current parent. then add it onto new parent. But it so simple and slow for sure because you need to select and remove and add just to change its ParentId.
I just wanted to know what is the best practices/or how to handle this kind of scenario.
In Native SQL what i just need to do is UPDATE <TABLE_CHILD> SET OWNER_ID = <ID> WHERE CHILD'S ID = <ID>. It's Simple.
But in Entity Framework. I can't even change its ParentId. only Child and its properties. It doesnt get updated.
I am new in Entity Framework. Thanks in Advance! Happy Coding!
You can do it by getting the Child-Table data and then add context.Entry(child).State = EntityState.Modified;
Something like this
var child = context.Childs.Where(a=>a.Id==id);
child.ParentEntityId = 2; // Assigning new FK
context.Childs.Attach(child);
context.Entry(child).State = EntityState.Modified;
context.SaveChanges();
you can try the above code, it should work, let me know if it didn't(with your current code.)
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly