Best way to update entity KEY using Entity Framework

时间:2016-05-11 11:29:19

标签: entity-framework

public void AlbumRenamed(string oldAlbumTitle, string newAlbumTitle)
    {
        var relatedAlbumInfoObj = AlbumInfoObjects.Find(oldAlbumTitle);
        AlbumInfoObjects.Remove(relatedAlbumInfoObj);
        SaveChanges();

        relatedAlbumInfoObj.AlbumTitle = newAlbumTitle;
        AlbumInfoObjects.Add(relatedAlbumInfoObj);
        SaveChanges();
    }

Well.. AlbumTitle property is a [Key]. So Entity Franework doesn't let me just to change it and save. Thus the only way to deal with that is to 1) delete old entity and 2) add new, updated, entity, right? But should I call SaveChanges() method every time I do deletion or addition? I am pretty new to Entity Framework and assume there is a faster way...

1 个答案:

答案 0 :(得分:0)

 public void AlbumRenamed(string oldAlbumTitle, string newAlbumTitle)
        {
        var relatedAlbumInfoObj =AlbumInfoObjects.FirstOrDefault(x=>x.AlbumTitle ==oldAlbumTitle);
        if(relatedAlbumInfoObj !=null)
          {
           relatedAlbumInfoObj.AlbumTitle =newAlbumTitle;
          SaveChanges();
          }
        }