我是代码新手,源自数据库上下文。这是我的模型的摘录。
[Table("pm_Material")]
public class Material
{
public Material()
{
this.ProductionStepLogs = new HashSet<ProductionStepLog>();
}
[Key]
public int MaterialId { get; set; }
public int MaterialTypeId { get; set; }
public string Description { get; set; }
public decimal CostRate { get; set; }
public virtual MaterialType MaterialType { get; set; }
public virtual ICollection<ProductionStepLog> ProductionStepLogs { get; set; }
}
[Table("pm_ProductionStepLog")]
public class ProductionStepLog
{
public ProductionStepLog()
{
this.Materials = new HashSet<Material>();
}
[Key]
public System.Guid ProductionStepLogId { get; set; }
public int ProductionStepId { get; set; }
public System.Guid ProductId { get; set; }
public Nullable<System.DateTime> BeginStep { get; set; }
public Nullable<System.DateTime> EndStep { get; set; }
public int UserId { get; set; }
public virtual Product Product { get; set; }
public virtual ProductionStep ProductionStep { get; set; }
public virtual ICollection<Material> Materials { get; set; }
}
数据库创建工作正常,但我想使用 [Table("pm_ProductionStepLogMaterials")] 指定自动生成的多对多表“ProductionStepLogMaterials”的名称。
这可能吗?
最佳答案
您应该重写您自己的 DBContext 类的 protected override void OnModelCreating(DbModelBuilder modelBuilder)
,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Material>()
.HasMany(a => a.ProductionStepLog)
.WithMany(a => a.Material)
.Map(x =>
{
x.ToTable("NameOfYourTable");
x.MapLeftKey("MaterialId");
x.MapRightKey("ProductionStepLogId");
});
}
关于c# - 代码首先多对多设置表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15783497/