1

I have a parent table and a child table.

Parent Table: int AID, nvarchar parentname, nvarchar description

Child Table: int CID, int AID, nvarchar childname, nvarchar address

Child table has got a foreign key(AID) from parent table. I need to display the list of Child table in view page. I'm new to asp.net mvc and the problem is, I'm not able to get the parentname to be displayed along with the childtable.

As we have foreign key, it should be possible to get the parentname using AID. Can anybody sort it out using some simple example. I'm struggling with this for the last 7hours.

Consider the Parent table to be an account and child to be a list of contacts associated with the account.

Parent Table => PID,PName, PAddress Child Table => CID,PID,CName,CAddress

Output Table => PName,CName,CAddress

Controller:

public ActionResult list()
{
var listing = db.child.FindContact().ToList();
return view(listing);
}

View snippet(.aspx):

<%: foreach(var a in Model) %>
{
<%: a.PName %>
<%: a.CName %>
<%: a.CAddress %>
}

Thanks.

1 Answer 1

1

Your Child object should have a property of type Parent. Check this. Then you can write a.Parent.PName on the view.

Sign up to request clarification or add additional context in comments.

3 Comments

But i get an error that, "Object reference not set".As it is creating the list dynamically, it should display the PName according the PID-foreign key.
Yep. I forgot one thing. During the load you should specify that you also need the parent. Should be something like: db.Child.Include("Parent").ToList()
Thank you very much. It works now. But db.Child.Include("Parent").ToList() can be used only for the .edmx model and it cannot be used for .dbml model I guess. Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.