locked
SaveChanges on LINQ to EF Datagrid Projection RRS feed

  • Question

  • Hello,

    Forgive me but I'm new to LINQ and EF and I may be way off base.

    I have a WPF datagrid that I want my users to be able to save changes to. I have a custom class that projects the correct datatype (not anonymous) and the datagrid compiles great. How do I save my changes. For example, if I enter data in the ActualSavings field, I want it to save back to the database. Here is my attempt.

    Here is the Custom Class:

    public class ProjectsBySite
        {
            public int IDSite { get; set; }
            public string SiteName { get; set; }
            public int IDProjects { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string ProjectName { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public DateTime SavingsDate { get; set; }
            public decimal PlannedSavings { get; set; }
            public decimal ActualSavings { get; set; }
        }

    Here is my cs with the RowEditEnding Event (error:'Data' does not exist in the current context on Data.SaveChages):

    public MainWindow()
            {
                InitializeComponent();
                dgProj.ItemsSource = GetProjectsBySiteID(1).ToList();          
            }
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
               
            }
    
            public List<ProjectsBySite> GetProjectsBySiteID(int siteid/*<---*/)
            {
                var prjs = new List<ProjectsBySite>();
                using (ProductivityEntities context = new ProductivityEntities())
                {
                    prjs = (from s in context.pt_Site
                             join ps in context.pt_ProjectsSites
                             on s.IDSite equals ps.Site_id
                             join p in context.pt_Projects
                             on ps.Project_id equals p.IDProjects
                             join pz in context.pt_ProjectSavings
                             on p.IDProjects equals pz.Project_id
                             join l in context.pt_Personnel
                             on p.Personnel_id equals l.IDPersonnel
                             where s.IDSite == siteid
                             select new ProjectsBySite
                             {
                                 IDSite = s.IDSite,
                                 SiteName = s.SiteName,
                                 IDProjects = p.IDProjects,
                                 FirstName = l.FirstName,
                                 LastName = l.LastName,
                                 ProjectName = p.ProjectName,
                                 StartDate = p.StartDate,
                                 EndDate = p.EndDate,
                                 SavingsDate = pz.SavingsDate,
                                 PlannedSavings = pz.PlannedSavings ?? 0,
                                 ActualSavings = pz.ActualSavings ?? 0
                             }).ToList();
                }
    
                return prjs;
            }
            private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
                ProjectsBySite proj = e.Row.DataContext as ProjectsBySite;
                Data.SaveChanges();
            }
        }

    And here is my xaml:

    <Window x:Class="Productivity_Tracking_Application.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:Productivity_Tracking_Application"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Grid Margin="0,0,18,0">
            <DataGrid x:Name="dgProj" HorizontalAlignment="Left" Height="379" Margin="10,10,0,0" VerticalAlignment="Top" Width="764"
                      AutoGenerateColumns="False" RowEditEnding="dgProj_RowEditEnding">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding IDSite, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Site ID" IsReadOnly="True" />
                    <DataGridTextColumn Binding="{Binding SiteName, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Site Name"/>
                    <DataGridTextColumn Binding="{Binding IDProject, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Project ID"/>
                    <DataGridTextColumn Binding="{Binding FirstName, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="150" Header="First Name"/>
                    <DataGridTextColumn Binding="{Binding LastName, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Last Name" IsReadOnly="True" />
                    <DataGridTextColumn Binding="{Binding ProjectName, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Project Name"/>
                    <DataGridTextColumn Binding="{Binding StartDate, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Start Date"/>
                    <DataGridTextColumn Binding="{Binding EndDate, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="150" Header="End Date"/>
                    <DataGridTextColumn Binding="{Binding SavingsDate, NotifyOnTargetUpdated=True,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Savings Date" IsReadOnly="True" />
                    <DataGridTextColumn Binding="{Binding PlannedSavings, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Planned Savings"/>
                    <DataGridTextColumn Binding="{Binding ActualSavings, NotifyOnSourceUpdated=True, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="100" Header="Actual Savings"/>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>


    Tuesday, December 4, 2018 9:01 PM

Answers

  • You should learn SoC.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    You should learn how to use MVVM.

    (a correction here)

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    //https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    You should learn how to use the DTO pattern.

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    You should learn how to use a layered pattern, which is much like n-tier.

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    You should learn how to use the DAO pattern.

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    DAL using DAO and DTO patterns for CRUD using EF. All DTO(s) are kept in classlib project called Entities, and all layers have reference to Entities an know about the DTO(s).

    WPF can be discussed at the WPF forum, including MVVM.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=wpf

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Entities;
    
    namespace DAL
    {
        public interface IDaoProject
        {
            DtoProject GetProjectById(int id);
            List<DtoProject> GetProjectsByUserId(string userid);
            void CreateProject(DtoProject dto);
            void UpdateProject(DtoProject dto);
            void DeleteProject(int id);
        }
    }
    
    =============================================
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Transactions;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoProject :IDaoProject
        {
            private readonly IOptions<ConnectionStrings> _options;
            
            public DaoProject(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserId;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    
            public List<DtoProject> GetProjectsByUserId(string userid)
            {
                var dtos = new List<DtoProject>();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    
                    dtos = (from a in context.Projects.Where(a => a.UserId.Contains(userid))
                        select new DtoProject
                        {
                            ProjectId = a.ProjectId,
                            ClientName = a.ClientName,
                            ProjectName = a.ProjectName,
                            Technology = a.Technology,
                            ProjectType = a.ProjectType,
                            UserId = a.UserId,
                            StartDate = a.StartDate,
                            EndDate = a.EndDate,
                            Cost = a.Cost
                        }).ToList();
                }
    
                return dtos;
            }
    
            public void CreateProject(DtoProject dto)
            {
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = new Projects
                    {
                        ClientName = dto.ClientName,
                        ProjectName = dto.ProjectName,
                        Technology = dto.Technology,
                        ProjectType = dto.ProjectType,
                        UserId = dto.UserId,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        Cost = dto.Cost
                    };
    
                    context.Projects.Add(project);
                    context.SaveChanges();
               }
            }
    
            public void UpdateProject(DtoProject dto)
            {
                var project = new Projects();
                
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserId = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectManagementContext(_options))
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Projects project;
    
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectManagementContext(_options))
                {
                   
                    var tasks = new DaoTask(_options).GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask(_options).DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }

    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }


    • Marked as answer by Justair07 Friday, December 7, 2018 2:37 AM
    • Edited by DA924x Sunday, December 9, 2018 2:14 AM
    Wednesday, December 5, 2018 2:12 AM

All replies

  • I think is not good to expose data entity to UI. If you have MVVM application there should exist some model for UI. You have it, great. If you take use cases of your code, there are two use cases.

    1) Show all projects

    2) Save project

    Use cases should be implemented inside application boundary. What does it means? There should be some class which implements use cases and creates facade of system. Some entities can go through system boundary. This entities are known as data transfer object (DTO). So facade needs to know how to map inner entity to DTO objects na view-model needs to know how to map DTO to model entity. 

    When you create application which is connected into some API (REST for example), or there is not any logic, there should be something like data layer which takes communication with API. Api method result is some DTO object which is deserialized into you entity in data layer. This entity can go into view-model which map it into model entity. 

    When you save, you map model entity back to data layer entity and send it into REST API (or database when you have application without logic). So if you have database it means model in UI is another object than data layer returns. There should be some class with Save method which find record in database and map UI model into data layer entity and save it into database.

    Tuesday, December 4, 2018 10:11 PM
  • You should learn SoC.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    You should learn how to use MVVM.

    (a correction here)

    https://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

    //https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    You should learn how to use the DTO pattern.

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    You should learn how to use a layered pattern, which is much like n-tier.

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    https://docs.microsoft.com/en-us/visualstudio/data-tools/n-tier-data-applications-overview?view=vs-2017

    You should learn how to use the DAO pattern.

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    DAL using DAO and DTO patterns for CRUD using EF. All DTO(s) are kept in classlib project called Entities, and all layers have reference to Entities an know about the DTO(s).

    WPF can be discussed at the WPF forum, including MVVM.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=wpf

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Entities;
    
    namespace DAL
    {
        public interface IDaoProject
        {
            DtoProject GetProjectById(int id);
            List<DtoProject> GetProjectsByUserId(string userid);
            void CreateProject(DtoProject dto);
            void UpdateProject(DtoProject dto);
            void DeleteProject(int id);
        }
    }
    
    =============================================
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Transactions;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoProject :IDaoProject
        {
            private readonly IOptions<ConnectionStrings> _options;
            
            public DaoProject(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserId;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    
            public List<DtoProject> GetProjectsByUserId(string userid)
            {
                var dtos = new List<DtoProject>();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    
                    dtos = (from a in context.Projects.Where(a => a.UserId.Contains(userid))
                        select new DtoProject
                        {
                            ProjectId = a.ProjectId,
                            ClientName = a.ClientName,
                            ProjectName = a.ProjectName,
                            Technology = a.Technology,
                            ProjectType = a.ProjectType,
                            UserId = a.UserId,
                            StartDate = a.StartDate,
                            EndDate = a.EndDate,
                            Cost = a.Cost
                        }).ToList();
                }
    
                return dtos;
            }
    
            public void CreateProject(DtoProject dto)
            {
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = new Projects
                    {
                        ClientName = dto.ClientName,
                        ProjectName = dto.ProjectName,
                        Technology = dto.Technology,
                        ProjectType = dto.ProjectType,
                        UserId = dto.UserId,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        Cost = dto.Cost
                    };
    
                    context.Projects.Add(project);
                    context.SaveChanges();
               }
            }
    
            public void UpdateProject(DtoProject dto)
            {
                var project = new Projects();
                
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserId = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectManagementContext(_options))
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Projects project;
    
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectManagementContext(_options))
                {
                   
                    var tasks = new DaoTask(_options).GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask(_options).DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }

    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }


    • Marked as answer by Justair07 Friday, December 7, 2018 2:37 AM
    • Edited by DA924x Sunday, December 9, 2018 2:14 AM
    Wednesday, December 5, 2018 2:12 AM
  • Hi Justair07,

    Thank you for posting here.

    Since your question is more related to EF, I will move it to EF forum for suitable support.

    https://social.msdn.microsoft.com/Forums/en-US/home?forum=adodotnetentityframework&filter=alltypes&sort=lastpostdesc

    The Visual C# forum discuss and ask questions about the C# programming language, IDE, libraries, samples, and tools.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 5, 2018 7:23 AM
  • Hi Justair07,

    >>If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. For example:

    If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. For example:

    ProjectsBySite proj = e.Row.DataContext as ProjectsBySite;
    
    using (var context = new YourDBContext())
    {
        context.Entry(proj ).State = EntityState.Modified;
    
        // Do some more work...  
    
        context.SaveChanges();
    }

    For more information, please refer to:

    https://docs.microsoft.com/en-us/ef/ef6/saving/change-tracking/entity-state

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, December 6, 2018 1:45 AM
  • Hi Zhanglong,

    I tried the following and got an error (see picture).

    private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
                ProjectsBySite proj = e.Row.DataContext as ProjectsBySite;
    
                using (var context = new ProductivityEntities())
                {
                    context.Entry(proj).State = EntityState.Modified;
    
                    proj.IDSite = proj.IDSite;
                    proj.SiteName = proj.SiteName;
                    proj.IDProjects = proj.IDProjects;
                    proj.FirstName = proj.FirstName;
                    proj.LastName = proj.LastName;
                    proj.ProjectName = proj.ProjectName;
                    proj.StartDate = proj.StartDate;
                    proj.EndDate = proj.EndDate;
                    proj.SavingsDate = proj.SavingsDate;
                    proj.PlannedSavings = proj.PlannedSavings;
                    proj.ActualSavings = proj.ActualSavings;
    
    
                    context.SaveChanges();
                }
            }

    Thursday, December 6, 2018 9:20 AM
  • You have to get the object within the context before you can change the object's state. It is also why I like using the DTO pattern,  leave the EF entity or entities  behind and sending the DTO or a collection of DTO(s) to the UI control letting the UI work with the DTO  or DTO(s) and send the DTO or DTO(s) back for CRUD operations with the database. It doesn't  matter if I am using ADO.NET, MS SQL Server command objects and T-SQL or I am using an ORM like EF.

    public void UpdateProject(DtoProject dto)
            {
                var project = new Projects();
                
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserId = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectManagementContext(_options))
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }


    Thursday, December 6, 2018 10:08 AM
  • Hi DA924x,

    Thank you for the articles. Very helpful and I'm learning a lot. I'm having trouble however putting the code into context of for my project. Here is my attempt but as you can see I'm messing some stuff up.

    public void UpdateProject(ProjectsBySite dto)
            {
                var project = new ProductivityEntities();
    
                using (var context = new ProductivityEntities(_options))
                {
                    project = (context.pt_Site.Where(a => a.IDSite == dto.IDSite)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.IDSite = dto.IDSite;
                    project.SiteName = dto.SiteName;
                    project.IDProjects = dto.IDProjects;
                    project.FirstName = dto.FirstName;
                    project.LastName = dto.LastName;
                    project.ProjectName = dto.ProjectName;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.SavingsDate = dto.SavingsDate;
                    project.PlannedSavings = dto.PlannedSavings;
                    project.ActualSavings = dto.ActualSavings;
                }
    
                using (var dbcontext = new ProjectManagementContext(_options))
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
            private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
                UpdateProject();
            }

    I also added this to mt ProjectsBySite custom class:


    • Edited by Justair07 Thursday, December 6, 2018 10:36 AM
    Thursday, December 6, 2018 10:31 AM
  • using (var context = new ProductivityEntities(_options))

    You don't have an _option that is special usage of passing the connectstring into the context, which being used in EF Core.

    You are not using EF Core. You are using EF6 or some other version of EF that is not EF Core. So it should be what you see below.

    using (var context = new ProductivityEntities())


    Thursday, December 6, 2018 10:38 AM
  • I also added this to mt ProjectsBySite custom class:

    You are not using the Data Access Object pattern in a Data Access Layer. So what you have done concerning the above is meaningless until you figure  out what a DAL is about and what the DAO pattern is about. 

    You basically have not schooled yourself on how to use OOP and how to design solutions effectively. 

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/42312ec0-3373-4466-a913-3acfb565a8a2/software-developer?forum=csharpgeneral

    Thursday, December 6, 2018 10:51 AM
  • Thank you. Yes, I'm using EF6. I fixed as suggested but still making some mistakes in my context referencing

    public void UpdateProject(ProjectsBySite dto)
            {
                var project = new ProductivityEntities();
    
                using (var context = new ProductivityEntities())
                {
                    project = (context.pt_Site.Where(a => a.IDSite == dto.IDSite)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.IDSite = dto.IDSite;
                    project.SiteName = dto.SiteName;
                    project.IDProjects = dto.IDProjects;
                    project.FirstName = dto.FirstName;
                    project.LastName = dto.LastName;
                    project.ProjectName = dto.ProjectName;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.SavingsDate = dto.SavingsDate;
                    project.PlannedSavings = dto.PlannedSavings;
                    project.ActualSavings = dto.ActualSavings;
                }
    
                using (var dbcontext = new ProjectManagementContext())
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
            private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
                UpdateProject();
            }

    Thursday, December 6, 2018 10:53 AM
  • Your usage

    var project = new ProductivityEntities();

    My usage....

    var project = new Projects();

    Your usage is tying to define the project class as ProductivityEntities that is the Dbcontext, the connection, that in no way defines the Product object.

    No, you have a class called Product,  Products or whatever the name of the class is named that defines a product on the EF virtual object model.

     I have to question your basic knowledge in using EF, as you should know what the context object is about for database connection  as opposed to an object on the model used for data persistence. 

    Thursday, December 6, 2018 11:15 AM
  • I also added this to mt ProjectsBySite custom class:

    You are not using the Data Access Object pattern in a Data Access Layer. So what you have done concerning the above is meaningless until you figure  out what a DAL is about and what the DAO pattern is about. 

    You basically have not schooled yourself on how to use OOP and how to design solutions effectively. 

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/42312ec0-3373-4466-a913-3acfb565a8a2/software-developer?forum=csharpgeneral

    So ProjectsBySite would be considered a Data Access Object? But this Object is only used to project my data to my datagrid? Now I just need to create a new DAO for capturing the changes and saving it? I read the articles and I'm still researching, I'm just trying to see if I'm understanding correctly. I also moved this to it's own class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Productivity_Tracking_Application
    {
        class DAL
        {
            public interface IDaoProject
            {
                ProjectsBySite GetProjectById(int id);
                List<ProjectsBySite> GetProjectsByUserId(string userid);
                void CreateProject(ProjectsBySite dto);
                void UpdateProject(ProjectsBySite dto);
                void DeleteProject(int id);
            }
        }
    }


    • Edited by Justair07 Thursday, December 6, 2018 11:26 AM
    Thursday, December 6, 2018 11:20 AM
  • I also added this to mt ProjectsBySite custom class:

    You are not using the Data Access Object pattern in a Data Access Layer. So what you have done concerning the above is meaningless until you figure  out what a DAL is about and what the DAO pattern is about. 

    You basically have not schooled yourself on how to use OOP and how to design solutions effectively. 

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/42312ec0-3373-4466-a913-3acfb565a8a2/software-developer?forum=csharpgeneral

    So ProjectsBySite would be considered a Data Access Object? But this Object is only used to project my data to my datagrid? NOw I just need to create a new DAO for capturing the changes and saving it? I read the articles and I'm still researching, I'm just trying to see if I'm understanding correctly. I also moved this to it's own class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Productivity_Tracking_Application
    {
        class DAL
        {
            public interface IDaoProject
            {
                ProjectsBySite GetProjectById(int id);
                List<ProjectsBySite> GetProjectsByUserId(string userid);
                void CreateProject(ProjectsBySite dto);
                void UpdateProject(ProjectsBySite dto);
                void DeleteProject(int id);
            }
        }
    }

    You should stop now and go do some reading on some links that I have presented on the basics in understanding the who, when, what and why basics in Object Oriented Programming and architecting .NET solutions using OOP. I have given you and or pointed you to the links.

    You have the cart before that horse trying to do things,  and you are still in the barn you never left it, becuase you don't understand the basics. It not that hard if read the information in the links.

    Thursday, December 6, 2018 11:39 AM
  • Your usage

    var project = new ProductivityEntities();

    My usage....

    var project = new Projects();

    Your usage is tying to define the project class as ProductivityEntities that is the Dbcontext, the connection, that in no way defines the Product object.

    No, you have a class called Product,  Products or whatever the name of the class is named that defines a product on the EF virtual object model.

     I have to question your basic knowledge in using EF, as you should know what the context object is about for database connection  as opposed to an object on the model used for data persistence. 

    Yeah, that was a silly mistake.

    I'm working on a project and out of my depth but I'm willing to learn. I'm reading all the articles you suggested and it is helping me understand the concept. That being said I have to admit, I'm still lost in converting your sample code into context for my project. I'm a beginner trying to tackle a project that is probably for and intermediate level coder.

    Thursday, December 6, 2018 11:41 AM

  • You should stop now and go do some reading on some links that I have presented on the basics in understanding the who, when, what and why basics in Object Oriented Programming and architecting .NET solutions using OOP. I have given you and or pointed you to the links.

    You have the cart before that horse trying to do things,  and you are still in the barn you never left it, becuase you don't understand the basics. It not that hard if read the information in the links.

    Agreed. I'll continue reading and post when I have a question with better understanding. Thank you.
    • Edited by Justair07 Thursday, December 6, 2018 11:44 AM
    Thursday, December 6, 2018 11:43 AM
  •  I got it!!

    After a lot of self teaching thanks to all the material DA924x shared! I moved my DAO's  and labled them more appropriately and was able to write back to my db:

    private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
              
                    DisplayProjectsBySite obj = e.Row.Item as DisplayProjectsBySite;
                    if (obj != null)
                    {
                        //see obj properties
                    }
                
                using (var context = new ProductivityEntities())
                {
                    var std = context.pt_ProjectSavings.Where(x => x.IDProjectSavings == obj.IDProjectSavings).First();
                    std.ActualSavings = obj.ActualSavings;
                    context.SaveChanges();
                }
            }
    I'm learning a lot!

    Friday, December 7, 2018 2:40 AM
  •  I got it!!

    After a lot of self teaching thanks to all the material DA924x shared! I moved my DAO's  and labled them more appropriately and was able to write back to my db:

    private void dgProj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
            {
              
                    DisplayProjectsBySite obj = e.Row.Item as DisplayProjectsBySite;
                    if (obj != null)
                    {
                        //see obj properties
                    }
                
                using (var context = new ProductivityEntities())
                {
                    var std = context.pt_ProjectSavings.Where(x => x.IDProjectSavings == obj.IDProjectSavings).First();
                    std.ActualSavings = obj.ActualSavings;
                    context.SaveChanges();
                }
            }
    I'm learning a lot!

    This is US street lingo.  --   You go boy! 
    Friday, December 7, 2018 4:20 AM
  • Hahaha
    Friday, December 7, 2018 1:17 PM