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

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현