【问题标题】:Foreign model not showing up外国模特没有出现
【发布时间】:2013-06-07 04:17:31
【问题描述】:

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

【问题讨论】:

  • 请提供您如何查询客户的代码。
  • 这只是一个db.Customers.ToList(),其中 db 是一个 dbContext。

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


【解决方案1】:

您还没有定义 Country 属性 overridable。尝试像这样更改您的模型:

public class Customer
    {
        .
        .            

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

    }

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

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

【讨论】:

  • 我认为不使用虚拟我本质上是急切加载?
猜你喜欢
  • 2021-09-13
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 2020-07-05
  • 2021-10-26
  • 2021-02-08
相关资源
最近更新 更多