好的我有两个课程:'计划'和'材料'。计划具有0..1材料,并且材料可以包含在多个计划中。创建数据库后,自动生成的列名为Material_MaterialId
,我希望将其命名为MaterialId
我的'计划'课程:
[Column("MaterialId")]
public virtual Material Material { get; set; }
我的'材料'课程:
public int MaterialId { get; set; }
但它似乎没有做任何事情。
答案 0 :(得分:2)
你应该用这个:
计划班级
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 class
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();
结果应该是这样的:
以您的名字命名:
[ForeignKey("MaterialFK")]
public virtual Material MyMaterial { get; set; } //your name
public int? MaterialFK { get; set; } //your name
答案 1 :(得分:0)
也许这样的事情可以解决问题:
[Column(Name="MaterialId")]
public virtual Material Material { get; set; }
否则,您可以通过使用类似于此的内容覆盖DbContext的OnModelCreating
方法来实现此目的:
public class YourContext: DbContext
{
public DbSet<Plan> Plans { get; set; }
public DbSet<Material> Materials { get; set; }
public YourContext()
: base("YourDb")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Plan>().
HasMany(c => c.Material).
Map(
m =>
{
m.MapLeftKey("MaterialId");
m.MapRightKey("PlanId");
m.ToTable("Plans");
});
}
}