1

我有一个包含国家/地区类的模型客户。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>
            }
4

1 回答 1

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();
于 2013-06-07T04:37:19.087 回答