Raj
Raj

Reputation: 73

How can I update table in Entity framework?

I am calling a web service from my MVC project and if it is successful then it returns process complete. This result, I am storing in variable called y.

var y = Here pass required parameters and if it is successfull store result in y

when I put breakpoint here and if process complete, I can see result in var y.

So if process complete I need to update my table. For this can I do like this ?

  if( y = "Process complete")
  {
     update table code here 
  }

and I don't know how to update table in Entity Framework. Here I need to update table called table1 and set column2 = 1, column 3 = value of column 4 where column 1 = value of column 1.

What I know for this is :

UPDATE tableName 
SET column2 = 1, column3 = context.FirstOrDefault().column4  
WHERE column1 =  context.FirstOrDefault(). column1

Update :

Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.

This is the code i am using to update my table :

      var rec = (from s in geton.table_1
      where s.on_id == geton.table_1.FirstOrDefault().on_id
      select s).FirstOrDefault();
      rec.export = 1;
      rec.on_date = geton.table_1.FirstOrDefault().on_date;
      geton.SaveChanges();

Upvotes: 0

Views: 3666

Answers (2)

Thewads
Thewads

Reputation: 5053

Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.

That sounds more like a Key error. Are you sure you have put a primary key on that table? If not then EF just uses the whole table as the key essentially

Upvotes: 0

Jatin patil
Jatin patil

Reputation: 4288

A new entity can be added to the context by calling the Add method on DbSet. This puts the entity into the Added state, meaning that it will be inserted into the database the next time that SaveChanges is called.

For example:

using (var context = new YourContext())
{
    var record = new TypeName { PropertyName = "Value" };
    context.EntityName.Add(record );
    context.SaveChanges();
}

For More Info :

http://msdn.microsoft.com/en-us/library/bb336792.aspx

http://msdn.microsoft.com/en-us/data/jj592676.aspx

http://www.entityframeworktutorial.net/significance-of-savechanges.aspx

Upvotes: 3

Related Questions