0

This is my database

The above is my database .I have for tables Contact,Countries,States,Cities.The Country in contact table is foreign key to the Id in countries table. And I am using entity framework to get the data.I am using database first approach.I am getting my Contact details by the following code

public class ContactManager
    {
        public static List<Contact> GetContacts()
        {
            using (var obj = new EntityDBConnectionString())
            {
                return obj.Contacts.ToList();
            }
        }
}

And in the Controller part I have like this

public ActionResult ViewContacts()
        {

            return View("ViewContacts",ContactManager.GetContacts());
        }

and atlast the View(cshtml)

@model  List<Entity.Data.Contact>

@{
    ViewBag.Title = "ViewContacts";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ViewContacts</h2>
<table style="font-family:'Segoe UI';font-size:20px;display:table" border="1" cell-spacing="1" >

        @foreach (var item in Model)
        {
             <tr style="border:1px solid black;padding-right:3px;background-color:lightblue;display:table-row">
    <td>@item.Id</td>
    <td>@item.Name</td>
    <td>@item.Mobile</td>
    <td>@item.EmailId</td>   
    <td>@item.Address</td>
    <td>@item.Country</td>
</tr>
        }

</table>

My problem is that I am getting the CountryId's in the output table as it is a foreign.Can I get the Country Name as output

The output I am getting is the below one

Output

How to get the Country name in the data part and pass to the controller and how to pass it to the view? Can anyone help me out .Thanks in advance!!!!!!

The below is my Contact class

public partial class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string EmailId { get; set; }
        public string Mobile { get; set; }
        public string Address { get; set; }
        public Nullable<int> City { get; set; }
        public Nullable<int> State { get; set; }
        public Nullable<int> Country { get; set; }

        public virtual City City1 { get; set; }
        public virtual Country Country1 { get; set; }
        public virtual State State1 { get; set; }
    }

and the edmx file isenter image description here

4

2 回答 2

3

IncludeCountry在EF查询中的表喜欢带国家

 public static List<Contact> GetContacts()
    {
        using (var obj = new EntityDBConnectionString())
        {
            return obj.Contacts.Include("Country").ToList();
        }
    }

并在您的视图中使用以下内容

@item.Country.Name
于 2013-10-02T10:45:06.997 回答
3

我假设您已经为国家和联系人表设置了数据库关系。现在在视图中,您可以使用

<td>@item.Country.Name</td>
于 2013-10-02T10:41:24.393 回答