代码首先设置多个表的多个名称

时间:2013-04-03 09:24:45

标签: c# ef-code-first

我是新手代码,并且是从DB Context派生的。这是我的模型的摘录。

[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”的名称。

这可能吗?

2 个答案:

答案 0 :(得分:2)

您应该覆盖您自己的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");
     });
}

答案 1 :(得分:1)

AFAIK,使用数据注释是不可能的,但可以使用配置流畅的API:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<E1Type>()
            .HasMany(e1 => e1.Collection)
            .WithMany(e2 => e2.Collection)
            .Map(config => config.ToTable("MyTable"));
    }