0

I am using ASP Core Web Application, MVC, Code First, with MySQL db. Here is the structure of my db: enter image description here

Here is code for those 2 models/classes:

=====This code is for 2nd EmployeeDate Table (Child)=====

[Table("employeedate")]
    {
        [Key]
        [Required]
        [Column("ID", TypeName = "int(10)")]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [Required]
        [Column("HiredDate", TypeName = "date")]
        public DateTime HiredDate { get; set; }

        [Column("FiredDate", TypeName = "date")]
        public DateTime? FiredDate { get; set; }

        [Required]
        //[Timestamp]
        [Column("ModifiedDate", TypeName = "datetime")]
        public DateTime ModifiedDate { get; set; }

        [Required]
        [Column("EmployeeID", TypeName = "int(10)")]
        public int EmployeeID { get; set; }

        // This attribute specifies which database field is the foreign key.
        [ForeignKey(nameof(EmployeeID))]

        // InverseProperty links the two virtual properties together.
        [InverseProperty(nameof(Models.Employee.EmployeeDates))]
        public virtual Employee Employee { get; set; }

    }
    
=====This code is for 1st Employee Table (Parent) =====

 [Table("employee")]
    public class Employee
    { 
        public Employee()
        {
            EmployeeDates = new HashSet<EmployeeDate>();
        }

        public string GetHiredDate
        {
            get
            {
                var hiredate = "this employee has never been hired";
                if (EmployeeDates.LastOrDefault() != null)
                {
                    hiredate = EmployeeDates.LastOrDefault().HiredDate.ToLongDateString();

                }
                return hiredate;
            }
        }
        
        public string GetFiredDate
        {
            get
            {
                var firedate = "active";
                if (EmployeeDates.LastOrDefault() != null && EmployeeDates.LastOrDefault().FiredDate.HasValue)
                {
                    firedate = EmployeeDates.LastOrDefault().FiredDate.Value.ToLongDateString();
                }
                return firedate;
            }
        }
        private DateTime hireddate = DateTime.Now;
        public DateTime HiredDate
        {
            get
            {
                return hireddate;
            }
        }
        public DateTime? FiredDate
        {
            get
            {
                DateTime? fireddate = null;
                if (EmployeeDates.LastOrDefault() != null && EmployeeDates.LastOrDefault().FiredDate.HasValue)
                {
                    fireddate = EmployeeDates.LastOrDefault().FiredDate.Value;
                }
                return fireddate;
            }
        }

        [Key]
        [Required]
        [Column("ID", TypeName = "int(10)")]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        [Required]
        [Column("FirstName", TypeName = "varchar(60)")]
        public string FirstName { get; set; }

        [Required]
        [Column("LastName", TypeName = "varchar(60)")]
        public string LastName { get; set; }

        [Required]
        [Column("Email", TypeName = "varchar(100)")]
        public string Email { get; set; }

        [Required]
        [Column("Phone", TypeName = "varchar(20)")]
        public string Phone { get; set; }

        [Required]
        [Range (16, 100)]
        [Column("Age", TypeName = "int(1)")]
        public int Age { get; set; }

        [Required]
        [Column("City", TypeName = "varchar(100)")]
        public string City { get; set; }

        [Required]
        [Column("Department", TypeName = "varchar(100)")]
        public string Department { get; set; }

        [InverseProperty(nameof(Models.EmployeeDate.Employee))]
 
        public virtual ICollection<EmployeeDate> EmployeeDates { get; set; }   
    }

CREATE method works fine including HiredDate (Not FiredDate). But EDIT works only for Employee properties , FiredDate property is not working. I can update everything else like First name, Age, etc but not FiredDate.

Here is code inside Controller:

// GET: Employee/Create
        public IActionResult Create(int ID =0)
        {
            return View(new Employee());
        }
        // POST: Employee/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(string firstName, string lastName, string email, string phone, int age, string city, string department, DateTime HiredDate)
        {
            //Nov20 add 2 objects and append HireDate separately from another Table
            var employee = new Employee { FirstName = firstName, LastName = lastName, Email = email, Phone = phone, Age = age, City = city, Department = department };
            var employeeDate = new EmployeeDate { HiredDate = HiredDate };
            employee.EmployeeDates.Add(employeeDate);
            if (ModelState.IsValid)
            {
                _context.Add(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }
        // GET: Employee/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var employee = await _context.Employees.FindAsync(id);
            if (employee == null)
            {
                return NotFound();
            }
            return View(employee);
        }
        // POST: Employee/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Email,Phone,Age,City,Department,FiredDate")] Employee employee)
        {
            if (id != employee.ID)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(employee);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeeExists(employee.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }

And finally Views: ====Edit==== enter image description here

====Create==== enter image description here

Btw when comment out FiredDate div inside Create View(because its not needed there) my project fails to build right away.

Any suggestions on what am i doing wrong? I'm new to this ASP Code First approach. Here are some more pics: enter image description here

AlecTech
  • 63
  • 8
  • You don't have a setter for FireDate in Employee class – pfloyd Nov 22 '20 at 08:01
  • `private DateTime? fireddate = DateTime.Now; public DateTime? FiredDate {get{DateTime? fireddate = null;if (EmployeeDates.LastOrDefault() != null &&EmployeeDates.LastOrDefault().FiredDate.HasValue) { fireddate = EmployeeDates.LastOrDefault().FiredDate.Value; } return fireddate; } set { fireddate = value; } }` As soon as I add setter, i get an error in browser: – AlecTech Nov 22 '20 at 16:48
  • You should have like this {get; set;} – pfloyd Nov 22 '20 at 16:52
  • I did this but still no luck: `private DateTime? fireddate = DateTime.Now; public DateTime? FiredDate { get; set; }` – AlecTech Nov 22 '20 at 16:58
  • HiredDate doesn't have {get;set;} in Employee class and it works fine – AlecTech Nov 22 '20 at 17:03

0 Answers0