Переглянути джерело

исправлена связь многие ко многим, добавлена функция удаления пользователя

ЧернощековаАР 2 тижнів тому
батько
коміт
c7c152ef11

+ 22 - 27
AvaloniaApplication2/ChernoshchekovaContext.cs

@@ -25,8 +25,6 @@ public partial class ChernoshchekovaContext : DbContext
 
     public virtual DbSet<User> Users { get; set; }
 
-    public virtual DbSet<UserTrait> UserTraits { get; set; }
-
     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
         => optionsBuilder.UseNpgsql("Host=edu.pg.ngknn.local;Port=5432;Database=chernoshchekova;Username=31P;Password=12345");
@@ -64,7 +62,6 @@ public partial class ChernoshchekovaContext : DbContext
 
             entity.HasOne(d => d.IdRoleNavigation).WithMany(p => p.Logineds)
                 .HasForeignKey(d => d.IdRole)
-                .OnDelete(DeleteBehavior.ClientSetNull)
                 .HasConstraintName("logined_role_fk");
         });
 
@@ -121,31 +118,29 @@ public partial class ChernoshchekovaContext : DbContext
                 .HasForeignKey<User>(d => d.IdUser)
                 .OnDelete(DeleteBehavior.ClientSetNull)
                 .HasConstraintName("users_logined_fk");
-        });
-
-        modelBuilder.Entity<UserTrait>(entity =>
-        {
-            entity.HasKey(e => e.Id).HasName("user_traits_pk");
-
-            entity.ToTable("user_traits");
 
-            entity.Property(e => e.Id).HasColumnName("id");
-            entity.Property(e => e.IdTrait)
-                .ValueGeneratedOnAdd()
-                .HasColumnName("id_trait");
-            entity.Property(e => e.IdUser)
-                .ValueGeneratedOnAdd()
-                .HasColumnName("id_user");
-
-            entity.HasOne(d => d.IdTraitNavigation).WithMany(p => p.UserTraits)
-                .HasForeignKey(d => d.IdTrait)
-                .OnDelete(DeleteBehavior.ClientSetNull)
-                .HasConstraintName("user_traits_trait_fk");
-
-            entity.HasOne(d => d.IdUserNavigation).WithMany(p => p.UserTraits)
-                .HasForeignKey(d => d.IdUser)
-                .OnDelete(DeleteBehavior.ClientSetNull)
-                .HasConstraintName("user_traits_users_fk");
+            entity.HasMany(d => d.Idtraits).WithMany(p => p.Idusers)
+                .UsingEntity<Dictionary<string, object>>(
+                    "Usertrait",
+                    r => r.HasOne<Trait>().WithMany()
+                        .HasForeignKey("Idtrait")
+                        .OnDelete(DeleteBehavior.ClientSetNull)
+                        .HasConstraintName("usertraits_trait_fk"),
+                    l => l.HasOne<User>().WithMany()
+                        .HasForeignKey("Iduser")
+                        .OnDelete(DeleteBehavior.ClientSetNull)
+                        .HasConstraintName("usertraits_users_fk"),
+                    j =>
+                    {
+                        j.HasKey("Iduser", "Idtrait").HasName("usertraits_pk");
+                        j.ToTable("usertraits");
+                        j.IndexerProperty<long>("Iduser")
+                            .ValueGeneratedOnAdd()
+                            .HasColumnName("iduser");
+                        j.IndexerProperty<long>("Idtrait")
+                            .ValueGeneratedOnAdd()
+                            .HasColumnName("idtrait");
+                    });
         });
 
         OnModelCreatingPartial(modelBuilder);

+ 1 - 1
AvaloniaApplication2/Trait.cs

@@ -9,5 +9,5 @@ public partial class Trait
 
     public string? Name { get; set; }
 
-    public virtual ICollection<UserTrait> UserTraits { get; set; } = new List<UserTrait>();
+    public virtual ICollection<User> Idusers { get; set; } = new List<User>();
 }

+ 1 - 1
AvaloniaApplication2/User.cs

@@ -19,5 +19,5 @@ public partial class User
 
     public virtual Logined IdUserNavigation { get; set; } = null!;
 
-    public virtual ICollection<UserTrait> UserTraits { get; set; } = new List<UserTrait>();
+    public virtual ICollection<Trait> Idtraits { get; set; } = new List<Trait>();
 }

+ 9 - 0
AvaloniaApplication2/ViewModels/PageForAdminViewModel.cs

@@ -21,6 +21,7 @@ namespace AvaloniaApplication2.ViewModels
         [ObservableProperty] Gender filteredGender;
 
         [ObservableProperty] List<Gender> gendersList;
+        public int ID => 1;
 
         public PageForAdminViewModel()
         {
@@ -61,5 +62,13 @@ namespace AvaloniaApplication2.ViewModels
             MainWindowViewModel.Self.UserProfileForAdminVM = new UserProfileForAdminViewModel(id);
             MainWindowViewModel.Self.Page = new UserProfileForAdmin();
         }
+
+        public void DeleteUser(int id)
+        {
+            Logined deletedUser = db.Logineds.FirstOrDefault(x => x.Id == id);
+            if (deletedUser != null) db.Logineds.Remove(deletedUser);
+            db.SaveChanges();
+            MainWindowViewModel.Self.Page = new PageForAdmin();
+        }
     }
 }

+ 1 - 1
AvaloniaApplication2/ViewModels/UserProfileForAdminViewModel.cs

@@ -25,7 +25,7 @@ namespace AvaloniaApplication2.ViewModels
         public UserProfileForAdminViewModel(int id)
         {
             GendersList = db.Genders.ToList();
-            editedUser = db.Users.Include(x => x.UserTraits).Include(x => x.GenderNavigation).FirstOrDefault(x => x.IdUser == id);
+            editedUser = db.Users.Include(x => x.Idtraits).Include(x => x.GenderNavigation).FirstOrDefault(x => x.IdUser == id);
             imageUser = EditedUser.Image != null ? new Bitmap(new MemoryStream(editedUser.Image)) : new Bitmap("C:/Users/ЧернощековаАР/source/repos/AvaloniaApplication2/AvaloniaApplication2/Assets/профиль.png");
         }
 

+ 1 - 1
AvaloniaApplication2/ViewModels/UserProfileViewModel.cs

@@ -25,7 +25,7 @@ namespace AvaloniaApplication2.ViewModels
         public UserProfileViewModel(int id)
         {
             GendersList = db.Genders.ToList();
-            editedUser = db.Users.Include(x => x.GenderNavigation).Include(x=>x.UserTraits).FirstOrDefault(x => x.IdUser == id);
+            editedUser = db.Users.Include(x => x.GenderNavigation).Include(x=>x.Idtraits).FirstOrDefault(x => x.IdUser == id);
             imageUser = EditedUser.Image != null ? new Bitmap(new MemoryStream(editedUser.Image)) : new Bitmap("C:/Users/ЧернощековаАР/source/repos/AvaloniaApplication2/AvaloniaApplication2/Assets/профиль.png");
         }
 

+ 14 - 1
AvaloniaApplication2/Views/PageForAdmin.axaml

@@ -6,7 +6,12 @@
              x:Class="AvaloniaApplication2.PageForAdmin"
 			 xmlns:vm="using:AvaloniaApplication2.ViewModels"
 			 x:DataType="vm:PageForAdminViewModel"
+			 xmlns:conv="using:AvaloniaApplication2.Resources"
 			 Background="LightGray">
+	<UserControl.Resources>
+		<conv:UserLogicalConverter x:Key="myUserLogicalConverter"/>
+	</UserControl.Resources>
+	
 	<Grid RowDefinitions="70,*">
 		<StackPanel Orientation="Vertical" Grid.Row="0">
 			<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
@@ -27,7 +32,7 @@
 					</ComboBox>
 				</StackPanel>
 			</StackPanel>
-			<ListBox ItemsSource="{Binding Users}" Grid.Row="1" Padding="5">
+				<ListBox ItemsSource="{Binding Users}" Grid.Row="1" Padding="5">
 				<ListBox.ItemTemplate>
 					<DataTemplate>
 						<StackPanel>
@@ -36,6 +41,14 @@
 							<TextBlock Text="{Binding GenderNavigation.NameGender, StringFormat=Пол: {0}}"/>
 							<TextBlock Text="{Binding IdUserNavigation.IdRoleNavigation.IdRole, StringFormat=Роль в системе: {0}}"/>
 							<Button Content="Изменить персональные данные пользователя" Command="{Binding $parent[UserControl].((vm:PageForAdminViewModel)DataContext).Press}" CommandParameter="{Binding IdUser}"/>
+							<Button Content="Удалить пользователя" Command="{Binding $parent[UserControl].((vm:PageForAdminViewModel)DataContext).DeleteUser}" CommandParameter="{Binding IdUser}">
+								<Button.IsVisible>
+									<MultiBinding Converter="{StaticResource myUserLogicalConverter}">
+										<Binding Path="IdUser"/>
+										<Binding Path="((vm:PageForAdminViewModel)DataContext).ID" RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=UserControl}"/>
+									</MultiBinding>
+								</Button.IsVisible>
+							</Button>
 						</StackPanel>
 					</DataTemplate>
 				</ListBox.ItemTemplate>

+ 2 - 2
AvaloniaApplication2/Views/UserProfile.axaml

@@ -30,10 +30,10 @@
 			</StackPanel>
 			<StackPanel Margin="120,15,0,0">
 				<TextBlock Text="Качества пользователя"/>
-				<ListBox ItemsSource="{Binding UserProfileVM.EditedUser.UserTraits}">
+				<ListBox ItemsSource="{Binding UserProfileVM.EditedUser.Idtraits}">
 					<ListBox.ItemTemplate>
 						<DataTemplate>
-							<TextBlock Text=""/>
+							<TextBlock Text="{Binding Name}"/>
 						</DataTemplate>
 					</ListBox.ItemTemplate>
 				</ListBox>

+ 32 - 16
AvaloniaApplication2/Views/UserProfileForAdmin.axaml

@@ -8,24 +8,40 @@
 			 x:DataType="vm:MainWindowViewModel"
 			 Background="LightGray">
 	<StackPanel>
-		<TextBlock Text="ПРОФИЛЬ ПОЛЬЗОВАТЕЛЯ" VerticalAlignment="Top" HorizontalAlignment="Center" FontStyle="Normal" FontWeight="Bold" FontSize="18" Padding="5" Classes="MyTB"/>
-		<TextBlock Text="Имя пользователя" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="0,0,70,0"/>
-		<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">
-			<TextBox Text="{Binding UserProfileForAdminVM.EditedUser.UserName}" Width="200" Height="30" Padding="5" Margin="5"/>
-			<Image Source="{Binding UserProfileForAdminVM.ImageUser}" Width="100" Height="100"/>
+		<TextBlock Text="ПРОФИЛЬ ПОЛЬЗОВАТЕЛЯ" VerticalAlignment="Top" HorizontalAlignment="Center" FontStyle="Normal" FontWeight="Bold" FontSize="18" Padding="5"/>
+		<StackPanel Orientation="Horizontal">
+			<StackPanel Margin="100,0,0,0">
+				<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">
+					<StackPanel Orientation="Vertical">
+						<TextBlock Text="Имя пользователя" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="0,10,70,0"/>
+						<TextBox Text="{Binding UserProfileForAdminVM.EditedUser.UserName}" Width="200" Height="30" Padding="5" Margin="5"/>
+					</StackPanel>
+					<Image Source="{Binding UserProfileForAdminVM.ImageUser}" Width="100" Height="100"/>
+				</StackPanel>
+				<TextBlock Text="Дата рождения" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="0,0,190,0"/>
+				<DatePicker SelectedDate="{ Binding UserProfileForAdminVM.DateTimeOffset}" HorizontalAlignment="Center" Width="300" Height="" Padding="5" Margin="5"/>
+				<ComboBox ItemsSource="{Binding UserProfileForAdminVM.GendersList}" SelectedItem="{Binding UserProfileForAdminVM.EditedUser.GenderNavigation}" HorizontalAlignment="Center" Width="150" Height="" HorizontalContentAlignment="Center">
+					<ComboBox.ItemTemplate>
+						<DataTemplate>
+							<TextBlock Text="{Binding NameGender}"/>
+						</DataTemplate>
+					</ComboBox.ItemTemplate>
+				</ComboBox>
+			</StackPanel>
+			<StackPanel Margin="120,15,0,0">
+				<TextBlock Text="Качества пользователя"/>
+				<ListBox ItemsSource="{Binding UserProfileForAdminVM.EditedUser.Idtraits}">
+					<ListBox.ItemTemplate>
+						<DataTemplate>
+							<TextBlock Text="{Binding Name}"/>
+						</DataTemplate>
+					</ListBox.ItemTemplate>
+				</ListBox>
+			</StackPanel>
 		</StackPanel>
-		<TextBlock Text="Дата рождения" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="0,0,90,0"/>
-		<DatePicker SelectedDate="{ Binding UserProfileForAdminVM.DateTimeOffset}" HorizontalAlignment="Center" Width="300" Height="" Padding="5" Margin="5"/>
-		<ComboBox ItemsSource="{Binding UserProfileForAdminVM.GendersList}" SelectedItem="{Binding UserProfileForAdminVM.EditedUser.GenderNavigation}" HorizontalAlignment="Center" Width="150" Height="" HorizontalContentAlignment="Center">
-			<ComboBox.ItemTemplate>
-				<DataTemplate>
-					<TextBlock Text="{Binding NameGender}"/>
-				</DataTemplate>
-			</ComboBox.ItemTemplate>
-		</ComboBox>
-		<Button Command="{Binding UserProfileForAdminVM.Save}" Content="Сохранить изменения" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="" Margin="5" Background="White" Foreground="Black" Width="" Height="30"/>
+		<Button Command="{Binding UserProfileForAdminVM.Save}" Content="СОХРАНИТЬ ИЗМЕНЕНИЯ" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="" Margin="5" Background="White" Foreground="Black" Width="" Height="30"/>
 		<Button Content="Выбрать изображение пользователя" Command="{Binding UserProfileForAdminVM.Image}" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="" Margin="5" Background="White" Foreground="Black" Width="" Height="30"/>
 		<Button Command="{Binding UserProfileForAdminVM.GoBack}" Content="ВЫХОД" VerticalAlignment="Top" HorizontalAlignment="Center" Padding="" Margin="5" Background="White" Foreground="Black" Width="" Height="30"/>
-		<TextBlock Text="Развлекаловка" HorizontalAlignment="Center" VerticalAlignment="Bottom" Classes="AnimatedTB"/>
+		<TextBlock Text="Развлекаловка" HorizontalAlignment="Center" VerticalAlignment="Bottom" Classes="AnimatedTB" Padding="0,40,0,0"/>
 	</StackPanel>
 </UserControl>