store a new user into a database using entity frameowkr in csharp

Assuming you have already set up your database and entity framework data context, you can store a new user into the database by following these steps:

  1. Create a new instance of the entity class representing the user you want to store:
main.cs
User newUser = new User();
newUser.Name = "John Smith";
newUser.Email = "john.smith@example.com";
98 chars
4 lines
  1. Add the new user to the DbSet representing the table in the database where users are stored:
main.cs
dbContext.Users.Add(newUser);
30 chars
2 lines
  1. Call the SaveChanges() method on the data context to persist the changes to the database:
main.cs
dbContext.SaveChanges();
25 chars
2 lines

Putting it all together, here's the code to store a new user using entity framework in C#:

main.cs
User newUser = new User();
newUser.Name = "John Smith";
newUser.Email = "john.smith@example.com";

dbContext.Users.Add(newUser);
dbContext.SaveChanges();
154 chars
7 lines

gistlibby LogSnag