MVC5: Foreign Key and data access

Vini

I am looking for selecting a list from my table based on another table. I need to retrieve system names that are part of a particular system family. i have already added foreign keys. I created a ViewModel containing both these classes but it throws a null pointer exception. I am new to MVC and I am not sure where I am wrong.

Model Class : Systems public class Systems {

    public int SystemsID { get; set; }
    public string SystemName { get; set; }
    public DateTime CreatedOn { get; set;}
    public string CreatedBy { get; set; }
    public int SystemFamilyID { get; set; }

    public virtual SystemFamily SystemFamily { get; set; }
}

Class SystemFamily

  public class SystemFamily
{

    public int SystemFamilyID { get; set;}
    public int SystemsID {get;set;}
    public string FamilyName { get; set; }
    public DateTime DateCreated { get; set; }
    public string CreatedBy { get; set; }

    public virtual ICollection<Systems> Systems { get; set; }


 }

ViewSystem is a method in my SystemFamilyController.

   public ActionResult ViewSystem(int? id)
    {
        var viewmodel = new Sys_SysFam();
        ViewBag.SystemFamilyID = id.Value;
        //if (id != null)
        //{
        //    ViewBag.SystemFamilyID = id.Value;
        //    viewmodel.Systems = viewmodel.SystemFamily.Where(
        //        i => i.SystemFamilyID == id.Value).Single().Systems;
        //}

        return View(viewmodel);
    }

the view :

@model SystemFam_System.ViewModel.Sys_SysFam
@{
ViewBag.Title = "ViewSystem";
 }

 <h2>ViewSystem</h2>

 <p>@ViewBag.SystemFamilyID</p>
 <table>
 @foreach (var item in Model.Systems)
 {
    string selectedRow = "";
    if (item.SystemFamilyID == ViewBag.SystemFamilyID)
    {
        //{
        //    selectedRow = "success";
        //}

        <tr class="@selectedRow">
            <td>
                @item.SystemName
            </td>
            <td>
                @item.SystemsID
            </td>
            <td>
                @item.SystemFamily
            </td>
        </tr>

      }
  }
</table>

I get null pointer Exception. I want to view the system that belongs to a particular family in view system.

Thanks in advance!! Vini

Edit :

public class Sys_SysFam
{
    public IEnumerable<Systems> Systems { get; set; }
    public SystemFamily SystemFamily { get; set; }
}
Ankit Sahrawat

Ok i have checked Sys_SysFam class too. As per your current code it will always throw null reference exception becasue in your controller code you are using:

public ActionResult ViewSystem(int? id)
    {
        var viewmodel = new Sys_SysFam();
        ViewBag.SystemFamilyID = id.Value;
        //if (id != null)
        //{
        //    ViewBag.SystemFamilyID = id.Value;
        //    viewmodel.Systems = viewmodel.SystemFamily.Where(
        //        i => i.SystemFamilyID == id.Value).Single().Systems;
        //}

        return View(viewmodel);
    }

here you are creating an object of Sys_SysFam as viewmodel and as your if part is commented so you are returning same viewmodel in which viewmodel.Systems will always be null. Here i did not see any request to database for getting the data from db but i think your data in viewmodel will come from database and if i uncomment your if condition then too you are not sending any request to database you are using same viewmodel object created above.

viewmodel.Systems = viewmodel.SystemFamily.Where(
                    i => i.SystemFamilyID == id.Value).Single().Systems;

in right side you are using viewmodel.SystemFamily with where condition but as viewmodel.SystemFamily is null it will always throw exception. Your solution should be something like this:

public ActionResult ViewSystem(int? id)
        {
            DataContext context = new DataContext();
            var viewmodel = new Sys_SysFam();
            ViewBag.SystemFamilyID = id.Value;
            if (id != null)
            {
                ViewBag.SystemFamilyID = id.Value;
                var sysFamily = context.SystemFamily.Include(x => x.Systems).FirstOrDefault(x => x.SystemFamilyID == id.Value);
                if (sysFamily != null)
                {
                    viewmodel.Systems = sysFamily.Systems;
                }
            }

            return View(viewmodel);
        }

here first i am creating object of DataContext which is my main context to access the database using entity framework. so first i will get the system family based on passed id from database and if system family is not null then i will set the data of systems in viewmodel. Include method will bring data for Systems based on system family from database.

Also improve your Sys_SysFam class to initialize systems so that it will not throw exception in your view when there is no data in viewmodel.Systems like this:

public class Sys_SysFam
    {
        public Sys_SysFam()
        {
            this.Systems = new List<Systems>();
        }

        public SystemFamily SystemFamily { get; set; }

        public IEnumerable<Systems> Systems { get; set; }
    }

Hope this will help you.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

mvc 5 code first userid as a Foreign Key - How to save data

From Dev

Foreign Key Access

From Dev

How to display foreign key value from a model to a cascaded dropdown list in mvc5?

From Dev

Handling Foreign Key Data

From Dev

Foreign Key Annotation in MVC

From Dev

MVC foreign key binding

From Dev

Foreign key C# MVC 5?

From Dev

Codeigniter Foreign Key data retrieve

From Dev

Insert foreign key data in database

From Dev

Hibernate: insert data with foreign key

From Dev

Yii CGridView data is foreign key

From Dev

Insert data into foreign key column

From Dev

Adding foreign key data to serializer?

From Dev

inserting data from primary key to foreign key

From Dev

How to get User Role for each user in Data access layer in Identity (MVC5)?

From Dev

How does Django foreign key access work

From Dev

Access SQLAlchemy model linked with foreign key

From Dev

Laravel access foreign key table column in blade

From Dev

ASP.NET MVC How to access Entity Framework generated foreign key?

From Dev

I can't save a foreign key into one to many table asp.net but data can be inserted asp.net mvc 5

From Dev

Foreign key not saving rails 5

From Dev

Primary Key / Foreign Key naming convention in MVC

From Dev

Updating data in a column based on a join with foreign key

From Dev

dummyrepository data foreign key with random id

From Dev

Error creating foreign key (check data types)

From Dev

Data not getting inserted into database with foreign key

From Dev

Create Foreign Key using Data Annotations

From Dev

Laravel migration foreign key depending on seed data

From Dev

Fetch data from models related with foreign key

Related Related

HotTag

Archive