Thomas Thomas - 13 days ago 5
C# Question

How to insert update multiple data in DB through Entity Framework

Suppose I have few records which i want to insert/update through EF.

public partial class Contact
{
public int ContactID { get; set; }
public string ContactPerson { get; set; }
public string EmailID { get; set; }
}

var _Contact = new list<Contact>();
_Contact.add(new Contact(){ContactID=1,ContactPerson="Dev",EmailID="d@gmail.com"});
_Contact.add(new Contact(){ContactID=2,ContactPerson="Ross",EmailID="a@gmail.com"});
_Contact.add(new Contact(){ContactID=3,ContactPerson="Martin",EmailID="b@gmail.com"});
_Contact.add(new Contact(){ContactID=4,ContactPerson="Moss",EmailID="c@gmail.com"});
_Contact.add(new Contact(){ContactID=5,ContactPerson="Koos",EmailID="q@gmail.com"});


With the help of a stored procedure, we can detect that any particular records exist or not, if exist then update will execute and if not exist then records will be inserted. i want to do the same through EF.......is it possible ?

I know that I can call SQL Server stored procedures from EF to achieve my goal but I am trying to know if I can do it in EF without calling a stored procedure?

If yes then discuss the same with sample code which check each records exist in db or not and if exist then it will update otherwise will insert. Looking for help.

Answer

Since EF 4.3 there is an AddOrUpdate ExtensionMethod for DbSet. in Namespace System.Data.Entity.Migrations

public partial class Contact
{
    public int ContactID { get; set; }
    public string ContactPerson { get; set; }
    public string EmailID { get; set; }
}

var _Contact=new list<Contact>();
_Contact.add(new Contact(){ContactID=1,ContactPerson="Dev",EmailID="d@gmail.com"});
_Contact.add(new Contact(){ContactID=2,ContactPerson="Ross",EmailID="a@gmail.com"});
_Contact.add(new Contact(){ContactID=3,ContactPerson="Martin",EmailID="b@gmail.com"});
_Contact.add(new Contact(){ContactID=4,ContactPerson="Moss",EmailID="c@gmail.com"});
_Contact.add(new Contact(){ContactID=5,ContactPerson="Koos",EmailID="q@gmail.com"});

// check by Primary key
context.Contacts.AddOrUpdate(_Contacts)
// or check by EmailID
context.Contacts.AddOrUpdate(p => p.EmailID, _Contacts)