【发布时间】:2013-01-17 08:03:49
【问题描述】:
我使用 EF-database-first 创建了一个 MVC4 Web 应用程序。这些表具有复合键 [ID、Name、EffDate],并且在数据库中没有定义外键: 比如Department偏类:
[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 */
}
Index 的 AllocationController 中的代码是: 公共行动结果索引() { return View(db.Allocation.Include(a => a.Department).ToList()); }
当我单击指向分配索引视图的链接时,我收到以下错误消息(在我停止调试之后):
“/”应用程序中的服务器错误。
指定的包含路径无效。实体类型 'KC_BillableUnit_TESTModel.Allocation' 未声明导航 名为“部门”的属性。
堆栈跟踪 [InvalidOperationException:指定的 包含路径无效。实体类型 '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,跨度跨度)+256 ....继续....
我尝试了各种注释组合,但都导致相同的错误。
如何让我的分配列表显示部门名称而不是部门 ID 编号?
【问题讨论】:
标签: asp.net-mvc-4 composite-key navigation-properties ef-database-first