Aniket Kamble
Aniket Kamble

Reputation: 19

Insert record in a sql table through inherited class in ASP.NET MVC 5

System generated Class of Guardian which is inherited from person

public class Guardian : Person
{
    public int GuardianId { get; set; }
    public string RelationWithApplicant { get; set; }

    public virtual Application Application { get; set; }
}

System generated Base Class of Person

public partial class Person
{
    public Person()
    {
        this.Coaches = new HashSet<Coach>();
        this.Applications = new HashSet<Application>();
    }

    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public System.DateTimeOffset BirthDate { get; set; }
    public string EmailId { get; set; }
    public string Height { get; set; }
    public string Weight { get; set; }
    public int LandlineNumber { get; set; }
    public int MobileNumber { get; set; }
    public string BuildingDetail { get; set; }
    public string StreetDetail { get; set; }
    public string AreaDetail { get; set; }
    public int CityId { get; set; }
    public int StateId { get; set; }
    public short CountryId { get; set; }
    public int AcademyRoleId { get; set; }

    public virtual AcademyRole AcademyRole { get; set; }
    public virtual Country Country { get; set; }
    public virtual State State { get; set; }
    public virtual City City { get; set; }
    public virtual ICollection<Coach> Coaches { get; set; }
    public virtual ICollection<Application> Applications { get; set; }
}

System generated Class of Application

public partial class Application
{
    public int ApplicationId { get; set; }
    public int PersonId { get; set; }
    public int CourseId { get; set; }
    public int ApplicationStatus { get; set; }
    public System.DateTime SubmissionDate { get; set; }

    public virtual Course Course { get; set; }
    public virtual Person Person { get; set; }
    public virtual Guardian Guardian { get; set; }
    public virtual Player Player { get; set; }
}

Custome class through which I am trying to exchange data from view to controller and viseversa

public partial class NKBAApplication
{
    public Course CourseInfo { get; set; }
    public Person PersonInfo { get; set; }
    public Guardian GuardianInfo { get; set; }
    public CourseType CourseTypeInfo { get; set; }
    public Application ApplicationInfo { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }
    public int SelectedCountry { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
    public int SelectedState { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }
    public int SelectedCity { get; set; }
    public IEnumerable<SelectListItem> AcademyRoles { get; set; }
    public int SelectedRole { get; set; }


}

I am new in C# MVC. Here I am trying to insert record in person table through application form. Actually without integrating gurdian in form, my records are saved but while I am trying to add the Guardian in form I dont know how to insert record in people table as person record stored in people and guardian also inherited from people table

Controller

    // GET: /Application/Create
    public ActionResult CreateApplication(int? id)
    {
        //            return RedirectToAction("Create");
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Course course = db.Courses.Find(id);
        if (course == null)
        {
            return HttpNotFound();
        }
        NKBAApplication nkbaApplication = new NKBAApplication();
        nkbaApplication.ApplicationInfo = new Application(); 
        nkbaApplication.ApplicationInfo.CourseId = course.CourseId;
        nkbaApplication.PersonInfo = new Person();
        nkbaApplication.CourseInfo = new Course();
        ViewBag.courseName = course.CourseType.CourseTypeName;
        ViewBag.courseStartDate = course.CourseStartDate;
        ViewBag.courseEndDate = course.CourseEndDate;
        ViewBag.courseLocation = course.CourseType.CourseTypeLocation;
        nkbaApplication.Countries = new SelectList(db.Countries, "CountryId", "CountryName");
        nkbaApplication.States = new SelectList(db.States, "StateId", "StateName");
        nkbaApplication.Cities = new SelectList(db.Cities, "CityId", "CityName");
        nkbaApplication.AcademyRoles = new SelectList(db.AcademyRoles, "AcademyRoleId", "AcademyRoleName");
        return View(nkbaApplication);

    }

    // POST: /Application/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateApplication(int? id, NKBAApplication nkbaApplication)
    {
        if (ModelState.IsValid)
        {
            if (nkbaApplication.SelectedCountry == 0 || nkbaApplication.SelectedCity == 0 || nkbaApplication.SelectedRole == 0)
            {
                return HttpNotFound();
            }

            Country country = db.Countries.Find(nkbaApplication.SelectedCountry);
            if (country == null)
            {
                return HttpNotFound();
            }
            nkbaApplication.PersonInfo.CountryId = country.CountryId;

            State state = db.States.Find(nkbaApplication.SelectedState);
            if (state == null)
            {
                return HttpNotFound();
            }
            nkbaApplication.PersonInfo.StateId = state.StateId;

            City city = db.Cities.Find(nkbaApplication.SelectedCity);
            if (city == null)
            {
                return HttpNotFound();
            }
            nkbaApplication.PersonInfo.CityId = city.CityId;

            AcademyRole academyrole = db.AcademyRoles.Find(nkbaApplication.SelectedRole);
            if (academyrole == null)
            {
                return HttpNotFound();
            }
            nkbaApplication.PersonInfo.AcademyRoleId = 2;

            db.People.Add((Person)nkbaApplication.PersonInfo);
            db.SaveChanges();
            db.Guardians.Add((Guardian)nkbaApplication.GuardianInfo);
            db.SaveChanges();
            nkbaApplication.ApplicationInfo.CourseId = id.Value;
            nkbaApplication.ApplicationInfo.ApplicationStatus = 0;      // 0 is Applied
            nkbaApplication.ApplicationInfo.PersonId = nkbaApplication.PersonInfo.PersonId;
            nkbaApplication.ApplicationInfo.SubmissionDate = Convert.ToDateTime(DateTime.Now.ToString());
            db.Applications.Add((Application)nkbaApplication.ApplicationInfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(nkbaApplication);
    }

Upvotes: 0

Views: 1021

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239320

This is more of an Entity Framework question than SQL or MVC. By default, EF handles inheritance via STI (Single Table Inheritance) also known as TPH (Table Per Hierarchy). So, when you say that Guardian is a Person, EF creates a dbo.Persons table with an extra column named Discriminator. If you save a Person, this column is blank, but if you save a Guardian, the column will be filled with the string value "Guardian". This then informs EF, when it retrieves the records, that it should instantiate Guardian rather than Person for that row. You can also use OfType<T> to select only certain types, for example, db.Persons.OfType<Guardian> will return only rows with a value of "Guardian" for the Discriminator column, which will all be instantiated as Guardian.

You can choose a different inheritance strategy, such as TPT (Table Per Type) or TPC (Table Per Concrete Class). TPT would result in both dbo.Guardians and dbo.Persons tables, where dbo.Guardians would have a foreign key to a row in dbo.Persons. TPC discards polymorphism completely and just has two completely separate tables with no link to each other.

Given that, then, unless you customize things, creating a Guardian creates a Person as well. You don't have to do anything extra, and you shouldn't be trying to add both at the same time. In other words, if you want a Guardian, don't add fields for an instance of Person, just add all the fields for the instance Guardian.

Upvotes: 1

Related Questions