Browse Source

Научились помещать картинки в базу

fly9024 1 year ago
parent
commit
5df08b7df0

+ 2 - 1
MyWpfApp/LoginedTable.cs

@@ -17,7 +17,8 @@ namespace MyWpfApp
         public int ID { get; set; }
         public string Login { get; set; }
         public int Password { get; set; }
-        public int IDRole { get; set; }    
+        public int IDRole { get; set; }
+    
         public virtual Roles Roles { get; set; }
         public virtual UserTable UserTable { get; set; }
     }

+ 1 - 1
MyWpfApp/MainWindow.xaml.cs

@@ -57,7 +57,7 @@ namespace MyWpfApp
             //преобразуем картинку в массив байт
             byte[] bytes = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
 
-
+            
             //преобразуем массив байт в BitmapImage (т.к. его можно помещать в ImageSource)          
             using (MemoryStream stream = new MemoryStream(bytes))
             {

+ 1 - 0
MyWpfApp/Model1.Context.cs

@@ -27,6 +27,7 @@ namespace MyWpfApp
     
         public virtual DbSet<LoginedTable> LoginedTable { get; set; }
         public virtual DbSet<Roles> Roles { get; set; }
+        public virtual DbSet<UserImages> UserImages { get; set; }
         public virtual DbSet<UserTable> UserTable { get; set; }
     }
 }

+ 62 - 1
MyWpfApp/Model1.edmx

@@ -21,6 +21,14 @@
           <Property Name="ID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
           <Property Name="Role" Type="nvarchar" MaxLength="50" Nullable="false" />
         </EntityType>
+        <EntityType Name="UserImages">
+          <Key>
+            <PropertyRef Name="ID" />
+          </Key>
+          <Property Name="ID" Type="int" Nullable="false" />
+          <Property Name="IDUser" Type="int" />
+          <Property Name="Image" Type="varbinary(max)" />
+        </EntityType>
         <EntityType Name="UserTable">
           <Key>
             <PropertyRef Name="ID" />
@@ -41,6 +49,18 @@
             </Dependent>
           </ReferentialConstraint>
         </Association>
+        <Association Name="FK_UserImages_UserTable">
+          <End Role="UserTable" Type="Self.UserTable" Multiplicity="0..1" />
+          <End Role="UserImages" Type="Self.UserImages" Multiplicity="*" />
+          <ReferentialConstraint>
+            <Principal Role="UserTable">
+              <PropertyRef Name="ID" />
+            </Principal>
+            <Dependent Role="UserImages">
+              <PropertyRef Name="IDUser" />
+            </Dependent>
+          </ReferentialConstraint>
+        </Association>
         <Association Name="FK_UserTable_LoginedTable">
           <End Role="LoginedTable" Type="Self.LoginedTable" Multiplicity="1" />
           <End Role="UserTable" Type="Self.UserTable" Multiplicity="0..1" />
@@ -56,11 +76,16 @@
         <EntityContainer Name="Хранилище Smerdova_PPModelContainer">
           <EntitySet Name="LoginedTable" EntityType="Self.LoginedTable" Schema="dbo" store:Type="Tables" />
           <EntitySet Name="Roles" EntityType="Self.Roles" Schema="dbo" store:Type="Tables" />
+          <EntitySet Name="UserImages" EntityType="Self.UserImages" Schema="dbo" store:Type="Tables" />
           <EntitySet Name="UserTable" EntityType="Self.UserTable" Schema="dbo" store:Type="Tables" />
           <AssociationSet Name="FK_LoginedTable_Roles" Association="Self.FK_LoginedTable_Roles">
             <End Role="Roles" EntitySet="Roles" />
             <End Role="LoginedTable" EntitySet="LoginedTable" />
           </AssociationSet>
+          <AssociationSet Name="FK_UserImages_UserTable" Association="Self.FK_UserImages_UserTable">
+            <End Role="UserTable" EntitySet="UserTable" />
+            <End Role="UserImages" EntitySet="UserImages" />
+          </AssociationSet>
           <AssociationSet Name="FK_UserTable_LoginedTable" Association="Self.FK_UserTable_LoginedTable">
             <End Role="LoginedTable" EntitySet="LoginedTable" />
             <End Role="UserTable" EntitySet="UserTable" />
@@ -73,6 +98,7 @@
         <EntityContainer Name="Smerdova_PPEntities" annotation:LazyLoadingEnabled="true">
           <EntitySet Name="LoginedTable" EntityType="Smerdova_PPModel.LoginedTable" />
           <EntitySet Name="Roles" EntityType="Smerdova_PPModel.Roles" />
+          <EntitySet Name="UserImages" EntityType="Smerdova_PPModel.UserImages" />
           <EntitySet Name="UserTable" EntityType="Smerdova_PPModel.UserTable" />
           <AssociationSet Name="FK_LoginedTable_Roles" Association="Smerdova_PPModel.FK_LoginedTable_Roles">
             <End Role="Roles" EntitySet="Roles" />
@@ -82,6 +108,10 @@
             <End Role="LoginedTable" EntitySet="LoginedTable" />
             <End Role="UserTable" EntitySet="UserTable" />
           </AssociationSet>
+          <AssociationSet Name="FK_UserImages_UserTable" Association="Smerdova_PPModel.FK_UserImages_UserTable">
+            <End Role="UserTable" EntitySet="UserTable" />
+            <End Role="UserImages" EntitySet="UserImages" />
+          </AssociationSet>
         </EntityContainer>
         <EntityType Name="LoginedTable">
           <Key>
@@ -102,6 +132,15 @@
           <Property Name="Role" Type="String" Nullable="false" MaxLength="50" FixedLength="false" Unicode="true" />
           <NavigationProperty Name="LoginedTable" Relationship="Smerdova_PPModel.FK_LoginedTable_Roles" FromRole="Roles" ToRole="LoginedTable" />
         </EntityType>
+        <EntityType Name="UserImages">
+          <Key>
+            <PropertyRef Name="ID" />
+          </Key>
+          <Property Name="ID" Type="Int32" Nullable="false" />
+          <Property Name="IDUser" Type="Int32" />
+          <Property Name="Image" Type="Binary" MaxLength="Max" FixedLength="false" />
+          <NavigationProperty Name="UserTable" Relationship="Smerdova_PPModel.FK_UserImages_UserTable" FromRole="UserImages" ToRole="UserTable" />
+        </EntityType>
         <EntityType Name="UserTable">
           <Key>
             <PropertyRef Name="ID" />
@@ -110,6 +149,7 @@
           <Property Name="Surname" Type="String" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="true" />
           <Property Name="Name" Type="String" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="true" />
           <NavigationProperty Name="LoginedTable" Relationship="Smerdova_PPModel.FK_UserTable_LoginedTable" FromRole="UserTable" ToRole="LoginedTable" />
+          <NavigationProperty Name="UserImages" Relationship="Smerdova_PPModel.FK_UserImages_UserTable" FromRole="UserTable" ToRole="UserImages" />
         </EntityType>
         <Association Name="FK_LoginedTable_Roles">
           <End Type="Smerdova_PPModel.Roles" Role="Roles" Multiplicity="1" />
@@ -135,7 +175,19 @@
             </Dependent>
           </ReferentialConstraint>
         </Association>
-      </Schema>
+        <Association Name="FK_UserImages_UserTable">
+          <End Type="Smerdova_PPModel.UserTable" Role="UserTable" Multiplicity="0..1" />
+          <End Type="Smerdova_PPModel.UserImages" Role="UserImages" Multiplicity="*" />
+          <ReferentialConstraint>
+            <Principal Role="UserTable">
+              <PropertyRef Name="ID" />
+            </Principal>
+            <Dependent Role="UserImages">
+              <PropertyRef Name="IDUser" />
+            </Dependent>
+          </ReferentialConstraint>
+        </Association>
+        </Schema>
     </edmx:ConceptualModels>
     <!-- C-S mapping content -->
     <edmx:Mappings>
@@ -159,6 +211,15 @@
               </MappingFragment>
             </EntityTypeMapping>
           </EntitySetMapping>
+          <EntitySetMapping Name="UserImages">
+            <EntityTypeMapping TypeName="Smerdova_PPModel.UserImages">
+              <MappingFragment StoreEntitySet="UserImages">
+                <ScalarProperty Name="Image" ColumnName="Image" />
+                <ScalarProperty Name="IDUser" ColumnName="IDUser" />
+                <ScalarProperty Name="ID" ColumnName="ID" />
+              </MappingFragment>
+            </EntityTypeMapping>
+          </EntitySetMapping>
           <EntitySetMapping Name="UserTable">
             <EntityTypeMapping TypeName="Smerdova_PPModel.UserTable">
               <MappingFragment StoreEntitySet="UserTable">

+ 3 - 1
MyWpfApp/Model1.edmx.diagram

@@ -7,9 +7,11 @@
       <Diagram DiagramId="ae5b2ce701874b25b282f6a8fdcd0ec7" Name="Diagram1">
         <EntityTypeShape EntityType="Smerdova_PPModel.LoginedTable" Width="1.5" PointX="3" PointY="0.875" />
         <EntityTypeShape EntityType="Smerdova_PPModel.Roles" Width="1.5" PointX="0.75" PointY="1.25" />
-        <EntityTypeShape EntityType="Smerdova_PPModel.UserTable" Width="1.5" PointX="5.25" PointY="1.125" />
+        <EntityTypeShape EntityType="Smerdova_PPModel.UserImages" Width="1.5" PointX="7.5" PointY="1.125" />
+        <EntityTypeShape EntityType="Smerdova_PPModel.UserTable" Width="1.5" PointX="5.25" PointY="1" />
         <AssociationConnector Association="Smerdova_PPModel.FK_LoginedTable_Roles" />
         <AssociationConnector Association="Smerdova_PPModel.FK_UserTable_LoginedTable" />
+        <AssociationConnector Association="Smerdova_PPModel.FK_UserImages_UserTable" />
       </Diagram>
     </edmx:Diagrams>
   </edmx:Designer>

+ 6 - 0
MyWpfApp/MyWpfApp.csproj

@@ -84,6 +84,9 @@
     <Compile Include="Roles.cs">
       <DependentUpon>Model1.tt</DependentUpon>
     </Compile>
+    <Compile Include="UserImages.cs">
+      <DependentUpon>Model1.tt</DependentUpon>
+    </Compile>
     <Compile Include="UserTable.cs">
       <DependentUpon>Model1.tt</DependentUpon>
     </Compile>
@@ -179,6 +182,9 @@
       <DependentUpon>Model1.edmx</DependentUpon>
       <LastGenOutput>Model1.cs</LastGenOutput>
     </Content>
+    <Resource Include="Resources\zaglushka.png">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </Resource>
     <Resource Include="Resources\logo.png">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </Resource>

+ 29 - 22
MyWpfApp/Pages/PageUserInfo.xaml

@@ -9,31 +9,38 @@
       Title="PageUserInfo">
 
     <Grid>
-        <StackPanel>
-            <TextBox Text="Информация о пользователе"/>
-            <GroupBox Header="Имя">
-                <TextBox Name="txtName" Text="{Binding UserTable.Name}"/>
-            </GroupBox>
-            <GroupBox Header="Фамилия">
-                <TextBox Name="txtSurname" Text="{Binding UserTable.Surname}"/>
-            </GroupBox>
-            <GroupBox Header="Логин">
-                <TextBox Text="{Binding LoginedTable.Login}"/>
-            </GroupBox>
-            <GroupBox Header="Пароль">
-                <TextBox Text="{Binding Password}"/>
-            </GroupBox>
-            <GroupBox Header="Роль пользователя">
-                <ComboBox Name="CBRoles" SelectedValue="{Binding LoginedTable.IDRole}"/>
-            </GroupBox>
+        <StackPanel Orientation="Horizontal" >
+            <StackPanel>
+                <Image Height="200" Width="200" Source="{Binding ZaglushkaPath}"/>
+                <Button x:Name="btnChangeUserImage" Content="Изменить изображение" Click="btnChangeUserImage_Click" Uid="{Binding ID}"/>
+            </StackPanel>
+            
 
-            <TextBlock x:Name="txtTitle" Text="Заголовок той страницы"/>
-            <Button Template="{StaticResource Template1}"  Content="{Binding Text,ElementName=txtTitle}"/>
+            <StackPanel>
+                <TextBox Text="Информация о пользователе"/>
+                <GroupBox Header="Имя">
+                    <TextBox Name="txtName" Text="{Binding UserTable.Name}"/>
+                </GroupBox>
+                <GroupBox Header="Фамилия">
+                    <TextBox Name="txtSurname" Text="{Binding UserTable.Surname}"/>
+                </GroupBox>
+                <GroupBox Header="Логин">
+                    <TextBox Text="{Binding LoginedTable.Login}"/>
+                </GroupBox>
+                <GroupBox Header="Пароль">
+                    <TextBox Text="{Binding Password}"/>
+                </GroupBox>
+                <GroupBox Header="Роль пользователя">
+                    <ComboBox Name="CBRoles" SelectedValue="{Binding LoginedTable.IDRole}"/>
+                </GroupBox>
 
+                <TextBlock x:Name="txtTitle" Text="Заголовок той страницы"/>
+                <Button Template="{StaticResource Template1}"  Content="{Binding Text,ElementName=txtTitle}"/>
 
-            <Button Content="Сохранить изменения" Name="BtnSave" Click="BtnSave_Click"/>
-            <Button Content="Назад" Name="BtnBack" Click="BtnBack_Click"/>
+
+                <Button Content="Сохранить изменения" Name="BtnSave" Click="BtnSave_Click"/>
+                <Button Content="Назад" Name="BtnBack" Click="BtnBack_Click"/>
+            </StackPanel>
         </StackPanel>
-        
     </Grid>
 </Page>

+ 44 - 3
MyWpfApp/Pages/PageUserInfo.xaml.cs

@@ -1,6 +1,10 @@
-using MyWpfApp.models;
+using Microsoft.Win32;
+using MyWpfApp.models;
 using System;
 using System.Collections.Generic;
+using System.Data.Entity;
+using System.Drawing;
+using System.IO;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
@@ -33,8 +37,10 @@ namespace MyWpfApp.Pages
         /// <param name="currentUser">Пользователь, о котором мы хотим видеть информацию</param>
         public PageUserInfo(LoginedTable currentUser)
         {
-            InitializeComponent();    
-            DataContext = new User(currentUser);
+            InitializeComponent();
+            user = new User(currentUser);
+            DataContext = user;
+
             status = 1;//редактируем существующего пользователя
             CBRoles.ItemsSource = Globals.MyGlobalConnection.Roles.ToList();//источник данных для элементов списка
             CBRoles.SelectedValuePath = "ID"; //какое значение (что конкретно) вернется при выборе пункта списка
@@ -71,5 +77,40 @@ namespace MyWpfApp.Pages
            Globals.MyGlobalConnection.SaveChanges();//сохраняем изменения в любом случае (ка при добавлении, так и при редактировании)
             MessageBox.Show("Сохранено");//информационное сообщение
         }
+
+       
+        private void btnChangeUserImage_Click(object sender, RoutedEventArgs e)
+        {
+            
+           
+            OpenFileDialog OFD = new OpenFileDialog();
+            OFD.Filter = "Все файлы | *.*; | Изображения |*.jpg;*.png;";
+            bool? success = OFD.ShowDialog();
+
+
+            ImageConverter imageConverter = new ImageConverter();
+
+            //создаем объект изображения по известному пути к картинке
+            System.Drawing.Image image = System.Drawing.Image.FromFile(OFD.FileName);
+
+            //преобразуем картинку в массив байт
+            byte[] bytes = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
+
+           // int IDUser = user.LoginedTable.ID;
+            Globals.MyGlobalConnection.UserImages.Add(new UserImages(){IDUser = user.UserTable.ID, Image = bytes });
+            Globals.MyGlobalConnection.SaveChanges();
+
+            ////преобразуем массив байт в BitmapImage (т.к. его можно помещать в ImageSource)          
+            //using (MemoryStream stream = new MemoryStream(bytes))
+            //{
+            //    var BMimage = new BitmapImage();
+            //    BMimage.BeginInit();
+            //    BMimage.CacheOption = BitmapCacheOption.OnLoad;
+            //    BMimage.StreamSource = stream;
+            //    BMimage.EndInit();
+            //    imageBindings.ImageSource = BMimage;
+            //}
+
+        }
     }
 }

+ 2 - 1
MyWpfApp/Pages/PageUserList.xaml

@@ -11,7 +11,8 @@
     <Page.Resources>
         <DataTemplate x:Key="DT1">
             <StackPanel Orientation="Horizontal">
-                <TextBox Text="Информация о пользователе"/>
+                <Image Height="50" Width="50" Source="{Binding ZaglushkaPath}"/>
+                <TextBox Text="{Binding ZaglushkaPath}"/>
                 <GroupBox Header="Имя">
                     <TextBlock Text="{Binding Name}"/>
                 </GroupBox>

+ 1 - 2
MyWpfApp/Pages/PageUserList.xaml.cs

@@ -43,8 +43,7 @@ namespace MyWpfApp.Pages
 
         private void BtnAddUser_Click(object sender, RoutedEventArgs e)//переход на страницу добавления нового пользователя
         {
-            Globals.MyGlobalFrame.Navigate(new PageUserInfo());//переход на страницу в режиме добавления
-            }
+            Globals.MyGlobalFrame.Navigate(new PageUserInfo());//переход на страницу в режиме добавления            
         }
 
        

BIN
MyWpfApp/Resources/zaglushka.png


+ 23 - 0
MyWpfApp/UserImages.cs

@@ -0,0 +1,23 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     Этот код создан по шаблону.
+//
+//     Изменения, вносимые в этот файл вручную, могут привести к непредвиденной работе приложения.
+//     Изменения, вносимые в этот файл вручную, будут перезаписаны при повторном создании кода.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace MyWpfApp
+{
+    using System;
+    using System.Collections.Generic;
+    
+    public partial class UserImages
+    {
+        public int ID { get; set; }
+        public Nullable<int> IDUser { get; set; }
+        public byte[] Image { get; set; }
+    
+        public virtual UserTable UserTable { get; set; }
+    }
+}

+ 8 - 0
MyWpfApp/UserTable.cs

@@ -14,10 +14,18 @@ namespace MyWpfApp
     
     public partial class UserTable
     {
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
+        public UserTable()
+        {
+            this.UserImages = new HashSet<UserImages>();
+        }
+    
         public int ID { get; set; }
         public string Surname { get; set; }
         public string Name { get; set; }
     
         public virtual LoginedTable LoginedTable { get; set; }
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
+        public virtual ICollection<UserImages> UserImages { get; set; }
     }
 }

+ 7 - 0
MyWpfApp/models/User.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
+using System.Windows;
 
 namespace MyWpfApp.models
 {
@@ -42,5 +43,11 @@ namespace MyWpfApp.models
         /// </summary>
         public UserTable UserTable { get { userTable.ID = loginedTable.ID; return userTable; } set => userTable = value; }
         public LoginedTable LoginedTable { get => loginedTable; set => loginedTable = value; }
+
+
+        string zaglushkaPath = "/Resources/zaglushka.png";
+
+        public string ZaglushkaPath { get => zaglushkaPath; }
+
     }
 }

+ 6 - 0
MyWpfApp/models/UserListModel.cs

@@ -72,6 +72,8 @@ namespace MyWpfApp.models
             }
         }
 
+       
+
 
         /// <summary>
         /// метод, в котором применяются сразу все доступные фильтры
@@ -85,6 +87,10 @@ namespace MyWpfApp.models
         }
 
 
+        string zaglushkaPath;
+
+        public string ZaglushkaPath { get { MessageBox.Show("ok"); return zaglushkaPath; } set => zaglushkaPath = "/Resources/zaglushka.png"; }
+
         public event PropertyChangedEventHandler PropertyChanged;
     }
 }