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'
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
add a comment |
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
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
add a comment |
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
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
c# entity-framework
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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.)
Thank you Steve! such great advices and i totally agree but i'm forced to work that way.
– Ibrahim Doqa
yesterday
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.)
Thank you Steve! such great advices and i totally agree but i'm forced to work that way.
– Ibrahim Doqa
yesterday
add a comment |
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.)
Thank you Steve! such great advices and i totally agree but i'm forced to work that way.
– Ibrahim Doqa
yesterday
add a comment |
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.)
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.)
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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