实体框架多对多关系添加/更新

本文关键字:更新 添加 框架 实体 关系 | 更新日期: 2023-09-27 18:11:36

我有两个实体,当我只更新或添加一个时,一切都ok

        db.Entry(user1).State = EntityState.Modified;
        foreach (var userAudio in user1.Audios)
        {
            db.Audios.AddOrUpdate(userAudio);
        }
        db.Users.AddOrUpdate(user1);
        db.SaveChanges();

但是如果我尝试添加/更新几个实体:

        db.Entry(user1).State = EntityState.Modified;
        foreach (var userAudio in user1.Audios)
        {
            db.Audios.AddOrUpdate(userAudio);
        }
        db.Users.AddOrUpdate(user1);
        db.Entry(user2).State = EntityState.Modified;
        foreach (var userAudio in user2.Audios)
        {
            db.Audios.AddOrUpdate(userAudio);
        }
        db.Users.AddOrUpdate(user2);
        db.SaveChanges();

抛出异常:

附加类型为"EfTest.Entities"的实体。音频失败是因为同一类型的另一个实体已经具有相同的主键价值…

也许是因为我在user1和user2中有相同的音频,EF无法插入它们…有人知道怎么解决这个问题吗?谢谢!

<

实体/strong>

namespace EfTest.Entities
{
    public class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public List<Audio> Audios { get; set; }
    }
    public class Audio
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }
        public string Artist { get; set; }
        public string Title { get; set; }
        public List<User> Users { get; set; }
    }
}

实体框架多对多关系添加/更新

不幸的是,我认为只有一种方法可以解决这个问题。它独立地添加实体,然后添加关系:

var userAudios = new List<Audio>();
// Key userId
// Value list of audiosIds
var userAudiosRelations = new List<Relation>();
foreach (var user in users)
{
    foreach (var audio in user.Audios)
    {
        if (!userAudios.Any(x => x.Id == audio.Id))
        {
            userAudios.Add(audio);
        }
        userAudiosRelations.Add(new Relation
        {
            User_Id = user.Id,
            Audio_Id = audio.Id
        });
    }
    user.Audios = null;
    db.Users.AddOrUpdate(user);
}
foreach (var audio in userAudios)
{
    db.Audios.AddOrUpdate(audio);
}
db.SaveChanges();
var existingRelations = db.Database.SqlQuery<Relation>("SELECT * FROM dbo.UserAudios").ToList();
var relationsToAdd =
    userAudiosRelations.Where(
        x => existingRelations.All(y => x.User_Id != y.User_Id || x.Audio_Id != y.Audio_Id)).ToList();
foreach (var relation in relationsToAdd)
{
    db.Database.ExecuteSqlCommand("INSERT INTO dbo.UserAudios (User_Id, Audio_Id) VALUES (@p0, @p1)",
        relation.User_Id, relation.Audio_Id);
}

其中关系模型:

public class Relation
{
    public int User_Id { get; set; }
    public int Audio_Id { get; set; }
}