试图更新不正确的表/ IEntityChangeTracker问题的多个实例

本文关键字:问题 实例 IEntityChangeTracker 更新 不正确 | 更新日期: 2023-09-27 18:05:09

这可能是一个愚蠢的问题,但我还是要问了。

一些事实。

  • 我使用实体6.0.0.0根据我的参考。
  • 我击中azure sql数据库。
  • 这个项目是基于mvc默认模板的东西。

所以我试图通过以下代码添加到表。请注意,每次只尝试了1条路径,而不是同时尝试了3条路径或所有路径的组合。

public User(UserModel userModel)
{
    using (var db = new SqlDogContext())
    {
        // Path 1 this seem like there is a better way but throws an exception anyways
        var sillyModel = new UserModel() { Id = userModel.Id };
        db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = RssLibObject});
        db.SaveChanges();
        db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = KodiLibObject});
        db.SaveChanges();
        db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = SoundCloudLibObject });
        db.SaveChanges();
        db.UserLibarys.Add(new UserLib {User = sillyModel, Libary = SpotifyBridgeObject });
        db.SaveChanges();
        // Path 2 I guess this would be ok
        var sillyModel = new UserModel() { Id = userModel.Id };
        db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = RssLibObject });
        db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = KodiLibObject });
        db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = SoundCloudLibObject });
        db.UserLibarys.Add(new UserLib { User = sillyModel, Libary = SpotifyBridgeObject });
        db.SaveChanges();
        // Path 3 - What i want to use..
        db.UserLibarys.Add(new UserLib { User = userModel, Libary = RssLibObject });
        db.UserLibarys.Add(new UserLib { User = userModel, Libary = KodiLibObject });
        db.UserLibarys.Add(new UserLib { User = userModel, Libary = SoundCloudLibObject });
        db.UserLibarys.Add(new UserLib { User = userModel, Libary = SpotifyBridgeObject });
        db.SaveChanges();
    }
}

对于路径1,我得到以下异常:

    {"Violation of PRIMARY KEY constraint 'PK_dbo.UserModels'. 
     Cannot insert duplicate key in object 'dbo.UserModels'. 
     The duplicate key value is (009d1c33-a3cf-49db-8243-ff8a447eff16).
     'r'nThe statement has been terminated."}

对于路径2,我得到了以下异常

    An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code

使用我在stackoverflow上找到的这个

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges
    db.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type '"{0}'" in state '"{1}'" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: '"{0}'", Error: '"{1}'"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

我得到以下消息

The User field is required.

这对我来说意义不大,因为在我看来,我正在提供它。

对于路径3,我得到以下异常:

    Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

这让我很困惑,因为它看起来像是在更新错误的表。这是我的模型

public class UserLib
{
    [Key]
    public int LibId { get; set; }
    public bool UserEnabled { get; set; }
    [Required]
    public virtual Lib Libary { get; set; }
    [Required]
    public virtual UserModel User { get; set; }
}
public class UserModel
{
    [Key, ForeignKey("ApplicationUser")]
    public string Id { get; set; }
    public virtual UserLib Libary { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}
public class Lib
{
    public string Name { get; set; }
    public string Logo { get; set; }
    [Key]
    public int LibId { get; set; }
    public virtual UserLib UserLib { get; set; }
}
public class ApplicationUser : IdentityUser
{
    public virtual UserModel MyUserModel { get; set; }
    // plus some other stuff in here that seems non relavent
}

这里是创建usermodel的地方

using (var db = new SqlDogContext())
{ 
     db.UserModels.Add(
        new UserModel()
        {
            Id = currentId
        }
    );
    db.SaveChanges();
    query = from b in db.UserModels
            where b.Id == currentId
            select b;
}

_CurrentUser = new User(query.First());

最终目标是为一个UserModel拥有一个用户一个用户模型用于多个用户库对于用户库来说,有一个库数据库的外键。

所以我可能犯了一个新手错误,但有人能看到我的问题:)。

试图更新不正确的表/ IEntityChangeTracker问题的多个实例

您正在尝试设置主键:var silymodel = new UserModel() {Id = UserModel。Id};然后多次存储,这是不可能的。让实体框架设置主键。还要注意的是,您不必在每次操作之后一直调用SaveChanges()。你可以做所有的插入,然后调用一次。