How do i save multiple objects at once on the database using entity frameworkEntity Framework vs LINQ to SQLUse of var keyword in C#Catch multiple exceptions at once?How do I view the SQL generated by the Entity Framework?How can I get Id of inserted entity in Entity framework?Validation failed for one or more entities while saving changes to SQL Server Database using Entity FrameworkFastest Way of Inserting in Entity FrameworkEntity Framework - Include Multiple Levels of PropertiesEntity Framework 5 Updating a RecordNo Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Is this toilet slogan correct usage of the English language?

Does IPv6 have similar concept of network mask?

Plot of a tornado-shaped surface

Limits and Infinite Integration by Parts

Non-trope happy ending?

Hero deduces identity of a killer

Can a Canadian Travel to the USA twice, less than 180 days each time?

Temporarily disable WLAN internet access for children, but allow it for adults

putting logo on same line but after title, latex

How should I respond when I lied about my education and the company finds out through background check?

How can "mimic phobia" be cured or prevented?

Why would a new[] expression ever invoke a destructor?

Unexpected behavior of the procedure `Area` on the object 'Polygon'

Does Doodling or Improvising on the Piano Have Any Benefits?

How could a planet have erratic days?

Mimic lecturing on blackboard, facing audience

How to fade a semiplane defined by line?

Why does a simple loop result in ASYNC_NETWORK_IO waits?

What exact color does ozone gas have?

Invalid date error by date command

How do you make your own symbol when Detexify fails?

Open a doc from terminal, but not by its name

Recommended PCB layout understanding - ADM2572 datasheet

Using substitution ciphers to generate new alphabets in a novel



How do i save multiple objects at once on the database using entity framework


Entity Framework vs LINQ to SQLUse of var keyword in C#Catch multiple exceptions at once?How do I view the SQL generated by the Entity Framework?How can I get Id of inserted entity in Entity framework?Validation failed for one or more entities while saving changes to SQL Server Database using Entity FrameworkFastest Way of Inserting in Entity FrameworkEntity Framework - Include Multiple Levels of PropertiesEntity Framework 5 Updating a RecordNo Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'













0















I am trying to add a list of objects and save them to the database once for all.
The issue is that only the last saved Id is saved in the database!
And my code goes like this:



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

var departmentCar = new DepartmentCar();
foreach (var item in carIds)
departmentCar.CarId = item;
departmentCar.DepartmentId = DepartmentId;
departmentCar.State = ObjectState.Added;
Save(departmentCar);




Note: I'm using Repository pattern










share|improve this question



















  • 1





    So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

    – Shahzad
    yesterday











  • add details, provide a definition of the Save method. is it contain context.savechanges()?

    – Nomi Ali
    yesterday











  • @shahzad it was by mistake, i edited it.

    – Ibrahim Doqa
    yesterday











  • @TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

    – Ibrahim Doqa
    yesterday















0















I am trying to add a list of objects and save them to the database once for all.
The issue is that only the last saved Id is saved in the database!
And my code goes like this:



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

var departmentCar = new DepartmentCar();
foreach (var item in carIds)
departmentCar.CarId = item;
departmentCar.DepartmentId = DepartmentId;
departmentCar.State = ObjectState.Added;
Save(departmentCar);




Note: I'm using Repository pattern










share|improve this question



















  • 1





    So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

    – Shahzad
    yesterday











  • add details, provide a definition of the Save method. is it contain context.savechanges()?

    – Nomi Ali
    yesterday











  • @shahzad it was by mistake, i edited it.

    – Ibrahim Doqa
    yesterday











  • @TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

    – Ibrahim Doqa
    yesterday













0












0








0








I am trying to add a list of objects and save them to the database once for all.
The issue is that only the last saved Id is saved in the database!
And my code goes like this:



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

var departmentCar = new DepartmentCar();
foreach (var item in carIds)
departmentCar.CarId = item;
departmentCar.DepartmentId = DepartmentId;
departmentCar.State = ObjectState.Added;
Save(departmentCar);




Note: I'm using Repository pattern










share|improve this question
















I am trying to add a list of objects and save them to the database once for all.
The issue is that only the last saved Id is saved in the database!
And my code goes like this:



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

var departmentCar = new DepartmentCar();
foreach (var item in carIds)
departmentCar.CarId = item;
departmentCar.DepartmentId = DepartmentId;
departmentCar.State = ObjectState.Added;
Save(departmentCar);




Note: I'm using Repository pattern







c# entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









TanvirArjel

9,43132147




9,43132147










asked yesterday









Ibrahim DoqaIbrahim Doqa

54




54







  • 1





    So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

    – Shahzad
    yesterday











  • add details, provide a definition of the Save method. is it contain context.savechanges()?

    – Nomi Ali
    yesterday











  • @shahzad it was by mistake, i edited it.

    – Ibrahim Doqa
    yesterday











  • @TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

    – Ibrahim Doqa
    yesterday












  • 1





    So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

    – Shahzad
    yesterday











  • add details, provide a definition of the Save method. is it contain context.savechanges()?

    – Nomi Ali
    yesterday











  • @shahzad it was by mistake, i edited it.

    – Ibrahim Doqa
    yesterday











  • @TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

    – Ibrahim Doqa
    yesterday







1




1





So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

– Shahzad
yesterday





So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar?

– Shahzad
yesterday













add details, provide a definition of the Save method. is it contain context.savechanges()?

– Nomi Ali
yesterday





add details, provide a definition of the Save method. is it contain context.savechanges()?

– Nomi Ali
yesterday













@shahzad it was by mistake, i edited it.

– Ibrahim Doqa
yesterday





@shahzad it was by mistake, i edited it.

– Ibrahim Doqa
yesterday













@TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

– Ibrahim Doqa
yesterday





@TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys.

– Ibrahim Doqa
yesterday












1 Answer
1






active

oldest

votes


















1














You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

foreach (var item in carIds)

var departmentCar = new DepartmentCar

CarId = item,
DepartmentId = DepartmentId
;
Save(departmentCar);




Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.



public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)

using (var context = new CarContext())

foreach (var carId in carIds)

var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)

car = new DepartmentCar CarId = carId ;
context.DepartmentCars.Add(car);

car.DepartmentId = departmentId;

context.SaveChanges();




This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.



From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)






share|improve this answer























  • Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

    – Ibrahim Doqa
    yesterday










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55278499%2fhow-do-i-save-multiple-objects-at-once-on-the-database-using-entity-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

foreach (var item in carIds)

var departmentCar = new DepartmentCar

CarId = item,
DepartmentId = DepartmentId
;
Save(departmentCar);




Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.



public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)

using (var context = new CarContext())

foreach (var carId in carIds)

var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)

car = new DepartmentCar CarId = carId ;
context.DepartmentCars.Add(car);

car.DepartmentId = departmentId;

context.SaveChanges();




This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.



From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)






share|improve this answer























  • Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

    – Ibrahim Doqa
    yesterday















1














You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

foreach (var item in carIds)

var departmentCar = new DepartmentCar

CarId = item,
DepartmentId = DepartmentId
;
Save(departmentCar);




Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.



public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)

using (var context = new CarContext())

foreach (var carId in carIds)

var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)

car = new DepartmentCar CarId = carId ;
context.DepartmentCars.Add(car);

car.DepartmentId = departmentId;

context.SaveChanges();




This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.



From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)






share|improve this answer























  • Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

    – Ibrahim Doqa
    yesterday













1












1








1







You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

foreach (var item in carIds)

var departmentCar = new DepartmentCar

CarId = item,
DepartmentId = DepartmentId
;
Save(departmentCar);




Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.



public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)

using (var context = new CarContext())

foreach (var carId in carIds)

var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)

car = new DepartmentCar CarId = carId ;
context.DepartmentCars.Add(car);

car.DepartmentId = departmentId;

context.SaveChanges();




This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.



From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)






share|improve this answer













You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.



public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)

foreach (var item in carIds)

var departmentCar = new DepartmentCar

CarId = item,
DepartmentId = DepartmentId
;
Save(departmentCar);




Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.



public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)

using (var context = new CarContext())

foreach (var carId in carIds)

var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)

car = new DepartmentCar CarId = carId ;
context.DepartmentCars.Add(car);

car.DepartmentId = departmentId;

context.SaveChanges();




This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.



From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)







share|improve this answer












share|improve this answer



share|improve this answer










answered yesterday









Steve PySteve Py

6,05311019




6,05311019












  • Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

    – Ibrahim Doqa
    yesterday

















  • Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

    – Ibrahim Doqa
    yesterday
















Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

– Ibrahim Doqa
yesterday





Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

– Ibrahim Doqa
yesterday



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55278499%2fhow-do-i-save-multiple-objects-at-once-on-the-database-using-entity-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript