你應該使用這樣的:
計劃類
public virtual Material Material { get; set; }
public int? MaterialId { get; set; } /* it prompt clr create foreign key MatherialId which referenced to MatherialId class of Matherial */
Matherial類
public int MaterialId { get; set; }
修訂
完整的解決方案
個
實體:
namespace MvcApplicationTest.Models
{
public class Material
{
public int MaterialId { get; set; }
public int Name { get; set; }
}
public class Plan
{
public int PlanId { get; set; }
public int Name { get; set; }
//full navigation property
public virtual Material Material { get; set; }
public int? MaterialId { get; set; }
//
}
public class TestContext : DbContext
{
public DbSet<Material> Materials { get; set; }
public DbSet<Plan> Plans { get; set; }
}
}
一些初始化在Global.asax中:
var context = new TestContext();
context.Database.CreateIfNotExists();
而且結果應該是這樣的:
![enter image description here](https://i.stack.imgur.com/4Vbpu.png)
爲了您的名字:
[ForeignKey("MaterialFK")]
public virtual Material MyMaterial { get; set; } //your name
public int? MaterialFK { get; set; } //your name
在我的觀點我不能使用MaterialId來訪問正常的其他propreties,因爲它是一個int('@ Html.DisplayNameFor(x => x.MaterialId.Name)'不起作用),但是「@ Html.DisplayNameFor x => x.Material.Name)'作品...這有點奇怪 –
爲什麼它很奇怪? MaterialId - 是db中的外鍵,但是Material - 它是EF類中的導航屬性,並且使用導航屬性可以獲取Matherial的名稱。 – testCoder
明白了,對我來說似乎很奇怪,不是很習慣它。但是我被迫從我的另一個班級給我的FK提供PK的名字,如果我想要另一個名字怎麼辦? –