我有一个相册实体:
--track-origins
其中包含Composer作为子对象:
public class Album
{
public Album() { }
[Key]
[Column("AlbumId")]
public int Id { get; set; }
public string Title { get; set; }
public int ReleaseYear { get; set; }
public int Rating { get; set; }
public int ComposerId { get; set; }
[ForeignKey("ComposerId")]
public Composer Composer { get; set; }
}
在我的相册更新方法中,我有以下正确运行的代码:
public class Composer
{
[Key]
[Column("ComposerId")]
public int Id { get; set; }
public string Name { get; set; }
}
以上代码尽管有效,但需要对数据库进行两次查询。我希望能够仅附加如下所示的更新的相册实体:
public void UpdateAlbum(Album album)
{
using (var context = new MusicCatelogContext())
{
try
{
Album albumEntity = context.Albums
.Where(a => a.Id.Equals(album.Id))
.Include(a => a.Composer)
.First();
Composer composerEntity = context.Composers
.Where(c => c.Id.Equals(album.Composer.Id))
.First();
context.Entry(albumEntity).CurrentValues.SetValues(album);
albumEntity.Composer = composerEntity;
context.SaveChanges();
}
但是,当我尝试这段代码时,尝试设置状态时会引发以下异常:
public void UpdateAlbum(Album album)
{
using (var context = new MusicCatelogContext())
{
try
{
context.Entry(album).State = EntityState.Modified;
context.SaveChanges();
}
我已经做了很多研究,但仍然不确定为什么会这样。我应该注意,在A referential integrity constraint violation occurred: The property value(s) of 'Composer.Id' on one end of a relationship do not match the property value(s) of 'Album.ComposerId' on the other end.
参数中传递给UpdateAlbum
的整个Composer对象是新的更新版本。
因此,我的问题是:
谢谢。