[英]Cannot SaveChanges() with DbContext Entity Framework Core
I am relatively new to EF core, so bare with me.我对 EF 核心比较陌生,所以对我来说很简单。
I am trying to create an application using the database-first approach (as code first did not work either) using Entity Framework Core.我正在尝试使用 Entity Framework Core 使用数据库优先方法(因为代码优先也不起作用)创建应用程序。 I have reverse engineered all the models using EF Core successfully, but upon trying to add new items to the database using my
DbContext
, I get a view nested exception message.我已经成功地使用 EF Core 对所有模型进行了逆向工程,但是在尝试使用我的
DbContext
将新项目添加到数据库时,我收到了一个视图嵌套异常消息。 My application utilizes two many to many relationships.我的应用程序使用两个多对多关系。
I am able to add singular items into the database, the problem arises with adding items into junction tables我能够将单个项目添加到数据库中,将项目添加到连接表中会出现问题
The error occurs after错误发生后
ctx.Usergorups.Add(newusergroup)
at在
ctx.SaveChanges();
and all following Add()
statements:以及所有以下
Add()
语句:
Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.Instance '((Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>)ctx.Usergroups).Instance' threw an exception of type 'System.NotImplementedException' System.IServiceProvider {System.NotImplementedException}
Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.Instance '((Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>)ctx.Usergroups).Instance' 引发了“System.NotImplementedException”System.IServiceProvider 类型的异常{System.NotImplementedException}
Spot where error occurs:发现错误发生的地方:
private void Create_Group(object sender, RoutedEventArgs e)
{
string groupname = this.namebox.Text;
if (groupname.Equals("Enter user friendly name") || (groupname.Equals("")))
{
MessageBox.Show("The group name cannot be the default. Enter something something descriptive");
return;
}
else
{
try
{
List<UserUserGroup> usergroups = new List<UserUserGroup>();
List<AccessGroupUserGroup> Accessgroupers = new List<AccessGroupUserGroup>();
Usergroups newusergroup = new Usergroups()
{
Name = groupname
};
var ctx = new FMS_SIRContext();
ctx.Usergroups.Add(newusergroup);
ctx.SaveChanges();
foreach (Users u in this.members.Where(u => u != null))
{
usergroups.Add(new UserUserGroup()
{
UserId = u.Id,
User = u,
UserGroupId = newusergroup.Id,
UserGroup = newusergroup
});
}
ctx.UserUserGroup.AddRange(usergroups);
foreach (Accessgroups a in this.acceessGroups.Where(a => a != null))
{
Accessgroupers.Add(new AccessGroupUserGroup()
{
AccessGroup = a,
AccessGroupId = a.Id,
UserGroup = newusergroup,
UserGroupId = newusergroup.Id
});
}
ctx.AccessGroupUserGroup.AddRange(Accessgroupers);
ctx.SaveChanges();
this.Close();
}
catch (Exception s)
{
MessageBox.Show(s.Data.ToString());
}
}
}
My DbContext
class:我的
DbContext
class:
public partial class FMS_SIRContext : DbContext
{
public FMS_SIRContext()
{
}
public FMS_SIRContext(DbContextOptions<FMS_SIRContext> options)
: base(options)
{
this.ChangeTracker.LazyLoadingEnabled = false;
}
public virtual DbSet<AccessGroupUserGroup> AccessGroupUserGroup { get; set; }
public virtual DbSet<Accessgroups> Accessgroups { get; set; }
public virtual DbSet<UserUserGroup> UserUserGroup { get; set; }
public virtual DbSet<Usergroups> Usergroups { get; set; }
public virtual DbSet<Users> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=az18w7413;Initial Catalog=****;Persist Security Info=True;User ID=******;Password=******;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AccessGroupUserGroup>(entity =>
{
entity.HasKey(e => new { e.AccessGroupId, e.UserGroupId });
entity.ToTable("AccessGroupUserGroup", "asps");
entity.HasIndex(e => e.UserGroupId);
entity.Property(e => e.AccessGroupId).HasColumnName("AccessGroupID");
entity.Property(e => e.UserGroupId).HasColumnName("UserGroupID");
entity.HasOne(d => d.AccessGroup)
.WithMany(p => p.AccessGroupUserGroup)
.HasForeignKey(d => d.AccessGroupId);
entity.HasOne(d => d.UserGroup)
.WithMany(p => p.AccessGroupUserGroup)
.HasForeignKey(d => d.UserGroupId);
});
modelBuilder.Entity<Accessgroups>(entity =>
{
entity.ToTable("accessgroups", "asps");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Itname).HasColumnName("ITNAME");
entity.Property(e => e.Name).HasColumnName("NAME");
entity.Property(e => e.Permission).HasColumnName("PERMISSION");
});
modelBuilder.Entity<UserUserGroup>(entity =>
{
entity.HasKey(e => new { e.UserId, e.UserGroupId });
entity.ToTable("UserUserGroup", "asps");
entity.HasIndex(e => e.UserGroupId);
entity.Property(e => e.UserId).HasColumnName("UserID");
entity.Property(e => e.UserGroupId).HasColumnName("UserGroupID");
entity.HasOne(d => d.UserGroup)
.WithMany(p => p.UserUserGroup)
.HasForeignKey(d => d.UserGroupId);
entity.HasOne(d => d.User)
.WithMany(p => p.UserUserGroup)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_UserUserGroup_User");
});
modelBuilder.Entity<Usergroups>(entity =>
{
entity.ToTable("usergroups", "asps");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Name).HasColumnName("NAME");
});
modelBuilder.Entity<Users>(entity =>
{
entity.ToTable("Users", "asps");
entity.HasIndex(e => e.Eid)
.HasName("IX_EID")
.IsUnique();
entity.HasIndex(e => e.Id)
.HasName("IX_ID");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Eid)
.HasColumnName("EID")
.HasMaxLength(50);
entity.Property(e => e.FirstName).HasMaxLength(100);
entity.Property(e => e.LastName).HasMaxLength(100);
entity.Property(e => e.LocationId).HasColumnName("LocationID");
entity.Property(e => e.Mail).HasMaxLength(200);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
I finally figured it out (8 hours later).我终于想通了(8小时后)。 It was not a dependency injection problem, but rather a ID assignment error.
这不是依赖注入问题,而是 ID 分配错误。 I assigned the ID of user, usergroup, accessgroup, and usergroup as well as assigned the objects, therefor making the ids 0 from the default constructor.
我分配了用户、用户组、访问组和用户组的 ID,并分配了对象,因此从默认构造函数中将 ID 设为 0。
private void Create_Group(object sender, RoutedEventArgs e)
{
string groupname = this.namebox.Text;
if (groupname.Equals("Enter user friendly name") || (groupname.Equals("")))
{
MessageBox.Show("The group name cannot be the default. Enter something something descriptive");
return;
}
else
{
try
{
List<UserUserGroup> usergroups = new List<UserUserGroup>();
List<AccessGroupUserGroup> Accessgroupers = new List<AccessGroupUserGroup>();
Usergroups newusergroup = new Usergroups()
{
Name = groupname
};
FMS_SIRContext ctx = new FMS_SIRContext();
ctx.Usergroups.Add(newusergroup);
ctx.SaveChanges();
foreach (Users u in members.Where(u => u != null))
{
usergroups.Add(new UserUserGroup()
{
UserId = u.Id,
//User = u,
UserGroupId = newusergroup.Id,
//UserGroup = newusergroup
});
}
//ctx.Usergroups.Add(newusergroup);
ctx.AddRange(usergroups);
foreach (Accessgroups a in this.acceessGroups.Where(a => a != null))
{
Accessgroupers.Add(new AccessGroupUserGroup()
{
//AccessGroup = a,
AccessGroupId = a.Id,
//UserGroup = newusergroup,
UserGroupId = newusergroup.Id
});
}
ctx.AddRange(Accessgroupers);
ctx.SaveChanges();
this.Close();
}
catch (Exception s)
{
MessageBox.Show(s.Data.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.