i\'m using Entity Framework 4.0 and having a silly problem that i can\'t figure out.
I have two tables:
This problem happens because you are referencing the same object more than once. This is not a limitation of EF, but rather a safety feature to ensure you are not inserting the same object with two different IDs. So to achieve what you are trying to do, is simply create a new object and add the newly created object to the database.
** This issue often happens inside loops. If you are using a while or foreach loop, make sure to have the New Created Object INSIDE the loop body.
try this:
Contact contact = dbContext.Contacts.Single(c => c.contactTypeId == 1234);
contact.contactTypeId = 4;
dbContext.AddObject(contact);
dbContext.SaveChanges();
Try
contact.ContactType = differentContactType;
or
contact.ContactTypeId = 3;
You are trying to set the Id of the ContactType (of the Contact) to 3.
first Remove next add
for simple
public static IEnumerable UserIntakeFoodEdit(FoodIntaked data)
{
DBContext db = new DBContext();
var q = db.User_Food_UserIntakeFood.AsQueryable();
var item = q.Where(f => f.PersonID == data.PersonID)
.Where(f => f.DateOfIntake == data.DateOfIntake)
.Where(f => f.MealTimeID == data.MealTimeIDOld)
.Where(f => f.NDB_No == data.NDB_No).FirstOrDefault();
item.Amount = (decimal)data.Amount;
item.WeightSeq = data.WeightSeq.ToString();
item.TotalAmount = (decimal)data.TotalAmount;
db.User_Food_UserIntakeFood.Remove(item);
db.SaveChanges();
item.MealTimeID = data.MealTimeID;//is key
db.User_Food_UserIntakeFood.Add(item);
db.SaveChanges();
return "Edit";
}
In my case the error was appearing as I removed the KEY attribute of the ID field.
// [Key]
public long Id { get; set; }
So just putting the attribute back in it's place, made everything working again!
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
In my case, I want to duplicate the object, but change the id, so I use this
Common.DataContext.Detach(object);
Work like a charm
in my case, i just set the primary key to table that was missing, re done the mappind edmx and it did work when you have the primary key tou would have only this
<PropertyRef Name="id" />
however if the primary key is not set, you would have
<PropertyRef Name="id" />
<PropertyRef Name="col1" />
<PropertyRef Name="col2" />
note that Juergen Fink answer is a work around