2013-04-03 80 views
2

我是新來的代碼第一,從DB上下文派生。這是我的模型的摘錄。代碼第一多到多集名稱

[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; } 
} 

的DB創建工作正常,但我想指定自動生成許多一對多表「ProductionStepLogMaterials」使用表(「pm_ProductionStepLogMaterials」)的名稱。

這可能嗎?

+0

只是名稱 ? – NSGaga

+0

對你有幫助嗎? – MikroDel

+0

@NSGaga,是的,只是名字。 – float

回答

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"); 
    }); 
} 
+0

這也不能用'DataAnnotations'實現嗎? – ecampver

+1

@ e.campver - 我認爲不是 - 導致DataAnnotations是整個Entity Framework功能的一部分。至今爲止,您可以將'DataAnnotations'用於最常見的場景,但不適用於所有場景 – MikroDel

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")); 
    } 
+0

upvote爲你投資的時間=) – MikroDel