-1

I have a table called Customers. On my website, the customer fills in his first name, last name, and email. I want to check if the email already exists in the database by what the customer fills in. If the customer exists, I would like to update the first name and last name (if they are different from the database).

The code I'm currently using for this is as following:

var email = vm.Reservation.Customer.Email; 

var customer = db.Customers.Where(x => x.Email == email).First();
if(customer != null)
{
    db.Entry(customer).State = !db.Customers.Any(c => c.Email == customer.Email) ? EntityState.Added : EntityState.Modified;
} else { 
    db.Customers.Add(vm.Reservation.Customer);
}

vm.Save();

However, it results in just adding a new customer with the modified username and password in the database with the same email.

How can I achieve this?

Thanks in advance.

Wolf
  • 13
  • 4
  • 2
    Does this answer your question? [Update Row if it Exists Else Insert Logic with Entity Framework](https://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework) – Klamsi Jun 17 '21 at 12:20

2 Answers2

0

You can do it like this:

var customer = db.Customers.FirstOrDefault(x => x.Email == email);

if(customer != null)
{
    //Set the values of 'customer' object using 'vm.Reservation.Customer'
    customer.Email = vm.Reservation.Customer.Email;
    customer.Field1 = vm.Reservation.Customer.Field1;
    customer.Field2 = vm.Reservation.Customer.Field2;

    db.Customers.Update(vm.Reservation.Customer);
} 
else { 
    db.Customers.Add(vm.Reservation.Customer);
}

db.SaveChanges();

Note: This code works for EntityFramework with PostgreSql database. So please mention your database you are using, which will be easier for you to find answers.

DiluzFerz
  • 53
  • 2
  • 11
0

try this


var email = vm.Reservation.Customer.Email; 
var customer = db.Customers.Where(x => x.Email == email).FirstOrDefault();

if(customer != null)
{
     customer.FirstName=vm.Reservation.Customer.FirstName; 
     customer.LastName=vm.Reservation.Customer.LastName; 
    db.Entry(customer).State =  EntityState.Modified;
} 
else 
{ 
    db.Customers.Add(vm.Reservation.Customer);
}

db.SaveChanges();
Serge
  • 40,935
  • 4
  • 18
  • 45