Reputation: 1151
I have a database containing sales of customers. I am trying to update 1 record using Entity Framework, but when I check my database, two records have been updated
My table is called Customers
and has these two records:
NameID GenderID ItemID ShopID Cost
--------------------------------------------------------
587651 1 464 9 NULL
587651 1 512 9 NULL
I want to update the first record which I am trying to do using Entity Framework.
This is my code:
using (var context = new Customers())
{
var _customers = (from all in context.Customers
where (all.NameID == 587651) &&
(all.GenderID == 1) &&
(all.ItemID == 464) &&
(all.ShopID == 9)
select all).First();
_customers.Cost = 100;
context.SaveChanges();
}
After saving the changes I get the following in my database:
NameID GenderID ItemID ShopID Cost
--------------------------------------------------------
587651 1 464 9 100
587651 1 512 9 100
Any idea what is going on?
Upvotes: 0
Views: 59
Reputation: 1151
Ok so I have now solved this, thanks to the comments above. The code that defined my table looked like this:
public partial class Customers
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int NameJID { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int GenderID { get; set; }
public int? ItemID { get; set; }
[Key]
[Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ShopID { get; set; }
public double? Cost { get; set; }
}
As you can see the primary key only includes NameID, GenderID and ShopID. Notice also how ItemID is nullable. I have now changed the code to this:
public partial class Customers
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int NameJID { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int GenderID { get; set; }
[Key]
[Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ItemID { get; set; }
[Key]
[Column(Order = 3)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ShopID { get; set; }
public double? Cost { get; set; }
}
Upvotes: 0