EF - 添加到由 Id 设置的关联
假设我有一个多对多的关系:
Song *---* Artist
我在我的代码中想要向歌曲添加艺术家。我知道艺术家的 ID,但没有 Artist
实体的实例。
目前我必须做类似的事情:
var artist = context.Artists.Single(a => a.Id == artistId);
song.Artists.Add(artist);
这涉及数据库查询。
多对多关系被建模为一个表:
SongId | ArtistId
-------+---------
出于性能原因,我想做的就是向该表添加一个条目,而不必转到数据库来加载我的一堆实体数据。不需要。
有没有办法用 EF 来做到这一点?例如,像这样的 API:
song.Artists.Add(artistId);
Say I have a many to many relationship:
Song *---* Artist
I'm at a point in my code where I want to add an artist to the song. I know the artist's ID, but I don't have an instance of the Artist
entity.
Currently I have to do something like:
var artist = context.Artists.Single(a => a.Id == artistId);
song.Artists.Add(artist);
This involves a DB query.
The many-to-many relationship is modelled as a table:
SongId | ArtistId
-------+---------
What I'd like to do, for performance reasons, is to just add an entry to this table without having to go to the DB to load a bunch of entity data that I don't need.
Is there a way to do this with EF? For example, an API like this:
song.Artists.Add(artistId);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用虚拟对象:
You can use dummy object: