0

How can I update all the records with Keyword_Id = 1 to Keyword_Id = 2?

public class KeywordAddressCategory
{
    [Key]
    [Column("Keyword_Id", Order = 0)]
    public int Keyword_Id { get; set; }

    [Key]
    [Column("Address_Id", Order = 1)]
    public int Address_Id { get; set; }

    [Key]
    [Column("Category_Id", Order = 2)]
    public int Category_Id { get; set; }
}

I get an exception saying that I can't update a key of the entity.

Thanks

Patrick
  • 2,995
  • 14
  • 64
  • 125
  • possible duplicate of [Update primary key value using entity framework](http://stackoverflow.com/questions/1367751/update-primary-key-value-using-entity-framework) – CodeCaster Sep 27 '13 at 12:00

1 Answers1

0

This is probably because those three properties are all part of the composite primary key, and as Entity Framework elegantly points out: you can't change the primary key value.

If this is at all an option, I would consider NOT using a composite primary key but a separate primary key for this class. You'll find it makes using foreign keys a lot simpler.

So, something like this:

[Key]
public int KeywordAddressCategoryId { get; set; }

public int Keyword_Id { get; set; }

public int Address_Id { get; set; }

public int Category_Id { get; set; }

With this system identity constraints, foreign keys, passing around id values as route values or as hidden fields in forms, ... all become much easier. And for your question: you can then easily change the Keyword_Id value because you CAN change a foreign key value easily.

I know this doesn't really answer your question, because I haven't told you how you can actually change the value, but I wanted to post this answer anyway so maybe you could reconsider your database structure.

Edit: see this question on how you can achieve what you want, if you really can't or aren't willing to change your DB structure: Update part of primary key Entity Framework 4.0

Community
  • 1
  • 1
Moeri
  • 9,104
  • 5
  • 43
  • 56
  • Thank you for your help, I will have to check the impact of this change in the structure of the database. Thanks again – Patrick Sep 27 '13 at 13:36