1

我已经使用EF-database-first创建了MVC4 Web应用程序。表具有复合键[ID,名称,EffDate],并在数据库中没有定义外键: 例如,部分类:带复合键的MVC4导航属性

[MetadataType(typeof(DepartmentMetadata))] 
public partial class Department 
{ 
    public int DeptID { get; set; } 
    public string DeptName { get; set; } 
    public System.DateTime EffDate { get; set; } 
    public string Status { get; set; } 
    public string RevenueAccount { get; set; } 
} 

部元数据类:

public class DepartmentMetadata 
{ 
    [Required] 
    public int DeptID { get; set; } 

    [Required] 
    [Display(Name = "Department Name")] 
    public string DeptName { get; set; } 

    [Required] 
    [Display(Name = "Effective Date")] 
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", NullDisplayText = "--", ConvertEmptyStringToNull = true)] 
    public System.DateTime EffDate { get; set; } 

    [Required] 
    public string Status { get; set; } 

    [Display(Name = "Revenue Account")] 
    [StringLength(10)] 
    public string RevenueAccount { get; set; } 
} 

分配表,这是指部门表。它还有一个组合键[DeptID,ProjectID,BillableUnitID,EffDate]。如果可以的话,我会声明DeptID字段是一个外键......但我不控制数据库,更重要的是我相信T-SQL将不允许外键成为组合键的一部分:

[MetadataType(typeof(AllocationMetadata))] 
public partial class Allocation 
{ 
    public int DeptID { get; set; } 
    public int ProjectID { get; set; } 
    public int BillableUnitID { get; set; } 
    public System.DateTime EffDate { get; set; } 
    public string Status { get; set; } 
    public decimal Allocation1 { get; set; } 
} 

这有效,但我得到了一列DeptID号码。我想要的是一列部门名称。

先前question指示我到虚拟导航性能,所以我加了他们:

[MetadataType(typeof(AllocationMetadata))] 
public partial class Allocation 
{ 
    [ForeignKey("Department")] 
    public int DeptID { get; set; } 
    public int ProjectID { get; set; } 
    public int BillableUnitID { get; set; } 
    public System.DateTime EffDate { get; set; } 
    public string Status { get; set; } 
    public decimal Allocation1 { get; set; } 

    public virtual Department Department { get; set; } /* navigation property */ 
} 

在AllocationController对指数的代码是: 公众的ActionResult指数(){ 回报 视图(db.Allocation .include(a => a.Department).ToList()); }

当我点击链接分配索引视图上,我得到这个错误信息(我停止调试后):在“/”应用

服务器错误。

指定的包含路径无效。实体类型 “KC_BillableUnit_TESTModel.Allocation”不声明导航 属性,名称为“部门”。

堆栈跟踪 [InvalidOperationException:指定的 包含路径无效。该的EntityType 'KC_BillableUnit_TESTModel.Allocation' 没有声明名称为 '部门' 导航 属性]
System.Data.Objects.Internal.ObjectFullSpanRewriter.ConvertSpanPath(SpanPathInfo parentInfo,List`1 navPropNames,的Int32 POS)+ 8355128
System.Data.Objects.Internal.ObjectFullSpanRewriter..ctor(DbCommandTree 树,DbExpression toRewrite,跨度跨度)256 ....继续....

我已经试过各种组合的注释,但都会导致相同的错误。

如何让我的分配列表显示部门名称而不是DeptID号码?

回答

0

当然你可以!我认为问题在于你只是在一边声明了导航属性(Allocation),但是你必须在双方声明这一点(Department也是)。

下必须解决您的问题:

[MetadataType(typeof(DepartmentMetadata))] 
public partial class Department 
{ 
    public Department() 
    { 
     this.Allocations = new HashSet<Allocation>(); 
    } 

    // properties ... 

    public virtual ICollection<Allocation> Allocations { get; set; } 
}