外国模特没有出现

时间:2013-06-07 04:17:31

标签: c# entity-framework asp.net-mvc-4 ef-code-first

我有一个包含国家/地区类的模型客户。 Country和Customer模型都映射到数据库。

    [Table("Customer")]
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerID { get; set; }
        public string Prefix { get; set; }
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        public string Address { get; set; }

        public string CountryID { get; set; }
        [ForeignKey("CountryID")]
        public Country Country { get; set; }

        public string City { get; set; }
        [Display(Name = "Postcode")]
        public string PostCode { get; set; }
        public string Email { get; set; }
        public string Remarks { get; set; }
        [Display(Name = "Telephone")]
        public string PhoneNumber { get; set; }
    }

尝试生成客户列表时。它没有看到生成国家名称。即使查看数据库时所有字段都已填满。

@foreach (var item in Model)
            {
                <tr>
                <td align="center"><input name="select_row[]" type="checkbox" /></td>
                <td>@Html.DisplayFor(modelItem => item.Prefix)</td>
                <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                <td>@Html.DisplayFor(modelItem => item.Country.Name)</td>
                <td>@Html.DisplayFor(modelItem => item.City)</td>
                <td>@Html.DisplayFor(modelItem => item.Address)</td>
                <td>@Html.DisplayFor(modelItem => item.PhoneNumber)</td>
                <td>@Html.DisplayFor(modelItem => item.Email)</td>
                <td>@Html.DisplayFor(modelItem => item.Remarks)</td>
                <td><span onclick="function_panel('customer','edit','@Url.Action("Edit", "Customer", new { id = item.CustomerID })')">edit</span>
                     | 
                    <span onclick="function_panel('customer','delete','@Url.Action("Delete","Customer")')">del</span></td>
            </tr>
            }

1 个答案:

答案 0 :(得分:1)

你没有定义Country属性overridable.try改变你的模型如下:

public class Customer
    {
        .
        .            

        public string CountryID { get; set; }
        [ForeignKey("CountryID")]
        public virtual Country Country { get; set; }
        .
        .

    }

或尝试按以下方式加载您的国家/地区:

var customers = db.Customers.Include("Country").ToList();