如何在asp.net mvc中显示导航属性的值

时间:2016-04-29 19:44:13

标签: asp.net-mvc entity-framework asp.net-mvc-4 lambda

CategoryName

索引方法:

public ActionResult Index(int? page)  
{  
   var data = objContext.Products.ToList().ToPagedList(page ?? 1, 1);  
   return View(data);  
}

View

1 个答案:

答案 0 :(得分:1)

如果在product poco中,您拥有Category Product的导航属性,只需使用:

@Html.DisplayNameFor(modelItem => model.Category.Title)

假设您的产品和类别如下:

public class Product {
    public int ID { get; set; }
    public string ProductName { get; set; }
    public int CategoryId { get; set; }

    // and other properties

    public virtual ProductCategory ProductCategory { get; set; }
}

public class ProductCategory {
    public int ID { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

product的地图定义中,您有:

internal class ProductMap : EntityTypeConfiguration<Product> {
    public ProductMap () {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties, for example
        this.Property(t => t.ProductName )
            .HasMaxLength(200);
        // Table Mappings
        this.ToTable("Product");

        //Relationships
        this.HasRequired(t => t.ProductCategory)
            .WithMany(t => t.Products)
            .HasForeignKey(d => d.CategoryId );

    }
}