Ich versuche, eine App mit C# EFCORE und SQL Server zu erstellen. Mein Problem ist es, einige grundlegende Konzepte rund um DB -Beziehungen zu definieren. Es wird meinen Mangel an Erfahrung und Verständnis zeigen, aber ich stecke auch in den frühen Phasen fest. Ich versuche, Benutzerauthentifizierung in die App zu implementieren. Ich habe eine Tabelle namens Modell / Tabelle für user_group_roles, die nur zwei Spalten für Namen und Beschreibung enthält. Ich habe eine andere Tabelle für User_groups, die einen Namen, eine Beschreibung, enthält. Angesichts der Tatsache, dass mehrere Gruppen von einem Benutzer definiert werden und dass ein bestimmter UserGrouProl mehrerer Benutzergruppen zugeordnet sein könnte, gehe ich davon aus, dass dies eine viel-zu-Viele-Beziehung ist. Eine neue Benutzergruppe sollte in der Lage sein, mit N -Anzahl von UserGrouproles definiert zu werden, aber es gibt keine Funktionalität für einen Benutzer, eine neue Rolle hinzuzufügen. Eine UserGrouprole soll stattdessen den Zugang zu einem anderen Teil der Anwendung direkt ermöglichen. Ich kann dazu führen, dass es in Bezug auf ein Hinzufügen funktioniert, aber dann funktioniert die Updates nicht. Updates scheint das Add zu brechen, und ich bin sicher, dass dies wahrscheinlich nur auf ein grundlegendes Missverständnis meiner Seite zurückzuführen ist, aber ich habe noch nicht festgestellt, was das sein könnte. Was ich bisher habe, ist Folgendes: < /p>
public class BaseEntity
{
[Key]
[JsonIgnore]
public int Id { get; set; }
public Guid EntityId { get; set; } = Guid.NewGuid();
[JsonIgnore]
public DateTime CreatedDate { get; set; } = DateTime.Now;
[JsonIgnore]
public DateTime UpdatedDate { get; set; }
[JsonIgnore]
public bool IsDeleted { get; set; } = false;
[JsonIgnore]
public int Version { get; set; }
}
public class UserGroup : BaseEntity
{
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public ICollection? RolesLink { get; set; } = [];
[JsonIgnore]
public List? Users { get; set; } = [];
}
public class UserGroupRole : BaseEntity
{
public string Name { get; set; }
public string Description { get; set; }
public ICollection? UserGroupsLink { get; set; } = [];
}
// defines the many to many join table
public class UserGroupUserGroupRoles
{
public int UserGroupId { get; set; }
public UserGroup UserGroup { get; set; }
public int UserGroupRoleId { get; set; }
public UserGroupRole UserGroupRole { get; set; }
}
public class ImportableUserGroup
{
public string Name { get; set; }
public string Description { get; set; }
public List Roles { get; set; } = [];
}
< /code>
// Db context
public DbSet UserGroupRoles { get; set; }
public DbSet UserGroups { get; set; }
public DbSet Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasKey(x => new { x.UserGroupId, x.UserGroupRoleId });
}
< /code>
// attempting to load user groups from a .json file in Service Layer based on
// settings in appsettings.json which points to the file to load and the filepath
// Based on the appsetttings.json file, load the data from the json file into the database.
public void LoadFileData()
{
foreach (var setting in _appSettings.DataLoaderSettings)
{
if (setting.EntityType == EntitySettingsName && setting.Enabled == true)
{
string jsonString = File.ReadAllText(Path.Combine(_appSettings.DataLoaderPath, setting.FileName));
IEnumerable userGroups = JsonSerializer.Deserialize(jsonString)!;
foreach (var userGroup in userGroups)
{
if (_userGroupRepository.Get(x => x.Name == userGroup.Name) != null)
continue;
AddImportable(userGroup);
}
}
}
}
public void AddImportable(ImportableUserGroup importedUserGroup)
{
// create a new User Group object from the file data
var newUserGroup = new UserGroup
{
Name = importedUserGroup.Name,
Description = importedUserGroup.Description,
};
if (importedUserGroup.Roles == null)
throw new Exception("UserGroupRoles not specified for Group: " + importedUserGroup.Name);
List userGroupUserGroupRoles = new List();
// the file data just includes a user group name, so we need to look up the UserGroupRole object
// and add to an array of UserGroupUserGroupRoles
foreach (var roleName in importedUserGroup.Roles)
{
UserGroupRole role = _userGroupRoleRepository.Get(x => x.Name == roleName);
if (role == null)
throw new Exception("UserGroupRole not found: " + roleName);
userGroupUserGroupRoles.Add(new UserGroupUserGroupRoles { UserGroupRole = role, UserGroup = newUserGroup });
}
//add the array of UserGroupUserGroupRoles to the new User Group object
newUserGroup.RolesLink = userGroupUserGroupRoles;
// add the new User Group object to the database
_userGroupRepository.Add(newUserGroup);
}
// attempting to update UserGroup in the Service layer
public void Update(UserGroup userGroup)
{
if (userGroup.RolesLink == null)
throw new Exception("UserGroupRoles not specified for Group: " + userGroup.Name);
UserGroup foundGroup = _userGroupRepository.Get(x => x.EntityId == userGroup.EntityId);
if (foundGroup == null)
throw new Exception("UserGroup not found: " + userGroup.Name);
List userGroupRoles = new List();
foreach (var userGroupRole in userGroup.RolesLink)
{
UserGroupRole role = _userGroupRoleRepository.Get(x => x.Name == userGroupRole.UserGroupRole.Name);
if (role == null)
throw new Exception("UserGroupRole not found: " + userGroupRole.UserGroupRole.Name);
userGroupRoles.Add(role);
}
foundGroup.Name = userGroup.Name;
foundGroup.Description = userGroup.Description;
foundGroup.RolesLink = userGroup.RolesLink;
_userGroupRepository.Update(foundGroup);
}
// repository layer add method
public void Add(T entity)
{
dbSet.Add(entity);
_db.SaveChanges();
}
// repository layer update method
public void Update(UserGroup entity)
{
var objFromDb = _db.UserGroups.Include(u => u.RolesLink).FirstOrDefault(u => u.EntityId == entity.EntityId);
if (objFromDb != null)
{
objFromDb.Name = entity.Name;
objFromDb.Description = entity.Description;
objFromDb.RolesLink?.Clear();
objFromDb.RolesLink = entity.RolesLink;
_db.UserGroups.Update(objFromDb);
_db.SaveChanges();
}
}
< /code>
Wenn es also versucht, die Dateidaten zu laden, erhalte ich diesen Fehler: < /p>
microsoft.entityFrameworkCore.dbupdateException HRESULT = 0x80131500
message = Es ist ein Fehler beim Speichern der Entitätsänderungen aufgetreten. Details finden Sie in der inneren Ausnahme. StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.c.b__112_0(DbContext _, ValueTuple`2 t)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at UserSecurity.DataAccess.Repositories.BaseRepository`1.Add(T entity) in ...\LensCS\LensUserSecurityApi\UserSecurity.DataAccess\Repositories\BaseRepository.cs:line 26
at ....Services.UserGroupService.AddImportable(ImportableUserGroup importedUserGroup) in ...\LensUserSecurityApi\Services\UserGroupService.cs:line 145
at .....Services.UserGroupService.LoadFileData() in ....\Services\UserGroupService.cs:line 68
at Program.$(String[] args) in ......\Program.cs:line 55
This exception was originally thrown at this call stack:
[External Code]
< /code>
Innere Ausnahme 1:
SQLEXception: Der explizite Wert für die Identitätsspalte in der Tabelle 'UserGrouproles' kann nicht einfügen, wenn Identity_insert auf OFF gesetzt ist. >
< /blockquote>
Dieser Fehler scheint zu implizieren, dass ich den UserGrouproles einen neuen Wert hinzufügen kann, indem ich einfach eine neue Benutzergruppe erstelle, was ich hier nicht versuche . Ich möchte einfach eine neue Benutzergruppe hinzufügen, die einen vorhandenen UserGrouprol
EntityFrameworkCore Viele bis viele SQLEXception: In der Tabelle kann man keinen expliziten Wert für die Identitätsspalt ⇐ C#
-
- Similar Topics
- Replies
- Views
- Last post