none
How to Insert/Modify data in my db table using EF from my viewmodel class RRS feed

  • Question

  • This is my viewmodel class

        public class StudentListViewModel
        {
            public List<SelectListItem> Countries { get; set; }
            public IList<Student> Students { get; set; }
            public List<Sex> Sex { get; set; }
    
            public StudentListViewModel()
            {
                Students = new List<Student>
                {
                    new Student
                    {
                        ID=1,Name="Keith",CountryID="0",SexID="F",
                        Hobbies= new List<Hobby>
                        {
                            new Hobby{ID=1,Name="Football",Checked=true},
                            new Hobby{ID=2,Name="Hocky",Checked=false},
                            new Hobby{ID=3,Name="Cricket",Checked=false}
                        }
            
                    },
    
                    new Student
                    {
                        ID=2,Name="Paul",CountryID="2",
                        Hobbies= new List<Hobby>
                        {
                            new Hobby{ID=1,Name="Football",Checked=false},
                            new Hobby{ID=2,Name="Hocky",Checked=true},
                            new Hobby{ID=3,Name="Cricket",Checked=false}
                        }
                    },
    
                    new Student
                    {
                        ID=3,Name="Sam",CountryID="3",
                        Hobbies= new List<Hobby>
                        {
                            new Hobby{ID=1,Name="Football",Checked=false},
                            new Hobby{ID=2,Name="Hocky",Checked=false},
                            new Hobby{ID=3,Name="Cricket",Checked=true}
                        }
                    }
                };
            }
    
            public List<Sex> GetSex()
            {
                Sex = new List<Sex>
                {
                    new Sex{ID="M",SexName="Male"},
                    new Sex{ID="F",SexName="Female"}
                };
    
                return Sex;
            }
    
            public List<SelectListItem> GetCountries()
            {
                Countries = new List<SelectListItem>
                {
                    new SelectListItem{Value="1",Text="India"},
                    new SelectListItem{Value="2",Text="UK"},
                    new SelectListItem{Value="3",Text="USA"}
                };
    
                return Countries;
            }
        }

    i want to insert/modify students data from my viewmodel class to student table. if data exist then update otherwise insert.

    student class has hobbies property. each student may have single or multiple hobbies. so how could i insert each student hobbies to studenthobbies db table from view model ?

    my model class as follows

    [Table("StudentMaster")]
    public partial class Student
    {
    	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    	public Student()
    	{
    	    Hobbies = new HashSet<Hobbies>();
    	}
    
    	public int ID { get; set; }
    
    	[StringLength(50)]
    	public string Name { get; set; }
    
    	public int? CountryID { get; set; }
    
    	[StringLength(1)]
    	public string SexID { get; set; }
    
    	public virtual MstSex MstSex { get; set; }
    
    	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    	public virtual ICollection<Hobbies> Hobbies { get; set; }
    }
        
    [Table("HobbiesMaster")]
    public partial class Hobbies
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Hobbies()
        {
    	Student = new HashSet<Student>();
        }
    
        public int ID { get; set; }
    
        [StringLength(50)]
        public string Name { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Student> Student { get; set; }
    }


    Model class

    [Table("StudentMaster")]
    public partial class Student
    {
    	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    	public Student()
    	{
    	    Hobbies = new HashSet<Hobbies>();
    	}
    
    	public int ID { get; set; }
    
    	[StringLength(50)]
    	public string Name { get; set; }
    
    	public int? CountryID { get; set; }
    
    	[StringLength(1)]
    	public string SexID { get; set; }
    
    	public virtual MstSex MstSex { get; set; }
    
    	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    	public virtual ICollection<Hobbies> Hobbies { get; set; }
    }
        
    [Table("HobbiesMaster")]
    public partial class Hobbies
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Hobbies()
        {
    	Student = new HashSet<Student>();
        }
    
        public int ID { get; set; }
    
        [StringLength(50)]
        public string Name { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Student> Student { get; set; }
    }

    dbcontext and relation

    public partial class Model1 : DbContext
        {
            public Model1()
                : base("name=Model12")
            {
            }
    
            public virtual DbSet<Hobbies> Hobbiess { get; set; }
            public virtual DbSet<MstSex> MstSexes { get; set; }
            public virtual DbSet<Student> Students { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Hobbies>()
                    .Property(e => e.Name)
                    .IsUnicode(false);
    
                modelBuilder.Entity<Hobbies>()
                    .HasMany(e => e.Students)
                    .WithMany(e => e.Hobbiess)
                    .Map(m => m.ToTable("StudentHobbies").MapLeftKey("HobbiesID").MapRightKey("StudentID"));
    
                modelBuilder.Entity<MstSex>()
                    .Property(e => e.ID)
                    .IsUnicode(false);
    
                modelBuilder.Entity<MstSex>()
                    .Property(e => e.Name)
                    .IsUnicode(false);
    
                modelBuilder.Entity<MstSex>()
                    .HasMany(e => e.Students)
                    .WithOptional(e => e.MstSex)
                    .HasForeignKey(e => e.SexID);
    
                modelBuilder.Entity<Student>()
                    .Property(e => e.Name)
                    .IsUnicode(false);
    
                modelBuilder.Entity<Student>()
                    .Property(e => e.SexID)
                    .IsUnicode(false);
            }
        }


    1) suppose my student view model has many student data then i have to insert those student data from viewmodel but if student exist then i have to modify data in db table.

    2) each student may have one or more hobbies then i need to first delete hobbies from studenthobbies table based on student id and then again add each student's hobbies in studenthobbies table.

    please guide me with sample code how to achieve what i am trying to do. thanks

    Wednesday, March 7, 2018 1:33 PM

Answers

  • http://www.c-sharpcorner.com/UploadFile/d87001/connected-and-disconnected-scenario-in-entity-framework/

    https://www.tutorialspoint.com/entity_framework/entity_framework_disconnected_entities.htm

    EF is always in a disconnected state with Web solution, because Web solutions are stateless.

    • Marked as answer by Sudip_inn Friday, March 9, 2018 12:36 PM
    Wednesday, March 7, 2018 4:12 PM
  • Hi Sudip_inn,

    According to your description, it seems that it is a many-to-many relationship insert and update, please refer to the following code.

    using (var db = new Model1())
                {
                    StudentListViewModel studentVM = new StudentListViewModel();
                    //studentVM.Sex = studentVM.GetSex();
                    //foreach (var item in studentVM.Sex)
                    //{
                    //    db.MstSexes.Add(item);
                    //    db.SaveChanges();
                    //}
                    if (studentVM.Students != null)
                    {
                        foreach (var item in studentVM.Students)
                        {
                            var student = db.Students.Find(item.ID);
                            if (student != null)
                            {
                                var deletedHobbies = student.Hobbies.ToList();
                                /* Find Added courses in student's Hobby collection by students' 
                                current Hobby list (came from client in disconnected scenario) minus 
                                students' existing courses (existing data from database)  */
                                var addedHobbies = item.Hobbies.ToList();
    
                                /* Remove deleted Hobbies from students' existing Hobby collection 
                                (existing data from database)*/
                                deletedHobbies.ForEach(c => student.Hobbies.Remove(c));
    
                                // Add new Hobbies
                                foreach (Hobby c in addedHobbies)
                                {
                                    /*Attach Hobbies because it came from client 
                                    as detached state in disconnected scenario*/
                                    if (db.Entry(c).State == EntityState.Detached)
                                        db.Hobbiess.Attach(c);
    
                                    //Add Hobby in existing student's Hobby collection
                                    student.Hobbies.Add(c);
                                }
                                
                            }
                            else
                            {
                                db.Students.Add(item);
                            }
                            db.SaveChanges();
                        }
                    }

    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.

    • Marked as answer by Sudip_inn Friday, March 9, 2018 12:36 PM
    Thursday, March 8, 2018 5:54 AM
    Moderator
  • Well, it's good that you are trying to implement some kind of Separation of Concerns in MVC by having database activity in the Model and not the Controller. IMO, you are not taking it far enough by using a DAL and possible DAO patterns in trying to use SoC.

    I'll show you.

    It's a two tier n-tier solution of presentation layer (MVC) and data access layer using the DAO pattern.

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    Take note on the word simplified.

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

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

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

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using DAL;
    using Entities;
    
    namespace MVC.Models
    {
        public class ProjectModels : IProjectModels
        {
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
                
                var dtos = new DaoProject().GetProjectsByUserId(userid);
    
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
       
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().CreateProject(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().UpdateProject(dto);
            }
    
            public void Delete(int id)
            {
                new DaoProject().DeleteProject(id);
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                project.ProjectTypes = new List<SelectListItem>
                {
                    new SelectListItem {Value = "1", Text = "Fixed Price"},
                    new SelectListItem {Value = "2", Text = "Time & Material"}
                };
    
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    
    --------------------------------------------------
    
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Transactions;
    using Entities;
    using DAL.Model;
    
    namespace DAL
    {
        public class DaoProject : IDaoProject
        {
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectMgmntEntities())
                {
                    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 ProjectMgmntEntities())
                {
    
                    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 ProjectMgmntEntities())
                {
                    var project = new Project
                    {
                        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 Project();
    
                using (var context = new ProjectMgmntEntities())
                {
                    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 ProjectMgmntEntities())
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Project project;
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectMgmntEntities())
                {
                    var tasks = new DaoTask().GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask().DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }
    

    • Marked as answer by Sudip_inn Tuesday, March 13, 2018 9:10 AM
    Friday, March 9, 2018 10:32 PM
  • If using EF in the traditional sense where EF is using auto incremented Identity as the primary-key, then one should be able to determine how to persist the EF entity for add or update by looking at the primary key property of the entity/object.

    If the primary ID property for the object > 0, then the object already exist in the database table, and it should be updated. 

    If the primary ID property for the object = 0, then the object should be inserted into the database table.

    That's how one tells what code path to take for add or update for an EF Entity.  

    • Marked as answer by Sudip_inn Wednesday, March 14, 2018 2:46 PM
    Tuesday, March 13, 2018 3:41 PM

All replies

  • http://www.c-sharpcorner.com/UploadFile/d87001/connected-and-disconnected-scenario-in-entity-framework/

    https://www.tutorialspoint.com/entity_framework/entity_framework_disconnected_entities.htm

    EF is always in a disconnected state with Web solution, because Web solutions are stateless.

    • Marked as answer by Sudip_inn Friday, March 9, 2018 12:36 PM
    Wednesday, March 7, 2018 4:12 PM
  • Hi Sudip_inn,

    According to your description, it seems that it is a many-to-many relationship insert and update, please refer to the following code.

    using (var db = new Model1())
                {
                    StudentListViewModel studentVM = new StudentListViewModel();
                    //studentVM.Sex = studentVM.GetSex();
                    //foreach (var item in studentVM.Sex)
                    //{
                    //    db.MstSexes.Add(item);
                    //    db.SaveChanges();
                    //}
                    if (studentVM.Students != null)
                    {
                        foreach (var item in studentVM.Students)
                        {
                            var student = db.Students.Find(item.ID);
                            if (student != null)
                            {
                                var deletedHobbies = student.Hobbies.ToList();
                                /* Find Added courses in student's Hobby collection by students' 
                                current Hobby list (came from client in disconnected scenario) minus 
                                students' existing courses (existing data from database)  */
                                var addedHobbies = item.Hobbies.ToList();
    
                                /* Remove deleted Hobbies from students' existing Hobby collection 
                                (existing data from database)*/
                                deletedHobbies.ForEach(c => student.Hobbies.Remove(c));
    
                                // Add new Hobbies
                                foreach (Hobby c in addedHobbies)
                                {
                                    /*Attach Hobbies because it came from client 
                                    as detached state in disconnected scenario*/
                                    if (db.Entry(c).State == EntityState.Detached)
                                        db.Hobbiess.Attach(c);
    
                                    //Add Hobby in existing student's Hobby collection
                                    student.Hobbies.Add(c);
                                }
                                
                            }
                            else
                            {
                                db.Students.Add(item);
                            }
                            db.SaveChanges();
                        }
                    }

    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.

    • Marked as answer by Sudip_inn Friday, March 9, 2018 12:36 PM
    Thursday, March 8, 2018 5:54 AM
    Moderator
  • i guess there is problem in the code

    1) this line deletedHobbies.ForEach(c => student.Hobbies.Remove(c)); will remove all hobbies from studenthobbies db table but i want to remove hobbies based on student id.

    2) i found no code to updated student data in student table table rather i found you insert student data  db.Students.Add(item);

    so please show me how to update student data in student table when found else insert.

    can we use AddOrUpdate extension. guide me with sample code.

    thanks

    Friday, March 9, 2018 12:36 PM
  • Well, it's good that you are trying to implement some kind of Separation of Concerns in MVC by having database activity in the Model and not the Controller. IMO, you are not taking it far enough by using a DAL and possible DAO patterns in trying to use SoC.

    I'll show you.

    It's a two tier n-tier solution of presentation layer (MVC) and data access layer using the DAO pattern.

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    Take note on the word simplified.

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

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

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

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using DAL;
    using Entities;
    
    namespace MVC.Models
    {
        public class ProjectModels : IProjectModels
        {
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
                
                var dtos = new DaoProject().GetProjectsByUserId(userid);
    
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
       
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().CreateProject(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().UpdateProject(dto);
            }
    
            public void Delete(int id)
            {
                new DaoProject().DeleteProject(id);
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                project.ProjectTypes = new List<SelectListItem>
                {
                    new SelectListItem {Value = "1", Text = "Fixed Price"},
                    new SelectListItem {Value = "2", Text = "Time & Material"}
                };
    
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    
    --------------------------------------------------
    
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Transactions;
    using Entities;
    using DAL.Model;
    
    namespace DAL
    {
        public class DaoProject : IDaoProject
        {
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectMgmntEntities())
                {
                    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 ProjectMgmntEntities())
                {
    
                    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 ProjectMgmntEntities())
                {
                    var project = new Project
                    {
                        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 Project();
    
                using (var context = new ProjectMgmntEntities())
                {
                    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 ProjectMgmntEntities())
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Project project;
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectMgmntEntities())
                {
                    var tasks = new DaoTask().GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask().DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }
    

    • Marked as answer by Sudip_inn Tuesday, March 13, 2018 9:10 AM
    Friday, March 9, 2018 10:32 PM
  • @Zhanglong Wu i asked a question based on your answer but still got no answer. please sir have a look at my question and share your answer. thanks

    i guess there is problem in the code

    1) this line deletedHobbies.ForEach(=> student.Hobbies.Remove(c)); will remove all hobbies from studenthobbies db table but i want to remove hobbies based on student id.

    2) i found no code to updated student data in student table table rather i found you insert student data  db.Students.Add(item);

    so please show me how to update student data in student table when found else insert.

    can we use AddOrUpdate extension. guide me with sample code.

    thanks

    Tuesday, March 13, 2018 9:11 AM
  • If using EF in the traditional sense where EF is using auto incremented Identity as the primary-key, then one should be able to determine how to persist the EF entity for add or update by looking at the primary key property of the entity/object.

    If the primary ID property for the object > 0, then the object already exist in the database table, and it should be updated. 

    If the primary ID property for the object = 0, then the object should be inserted into the database table.

    That's how one tells what code path to take for add or update for an EF Entity.  

    • Marked as answer by Sudip_inn Wednesday, March 14, 2018 2:46 PM
    Tuesday, March 13, 2018 3:41 PM