c# - 代码首先多对多设置表名称

标签 c# ef-code-first

我是代码新手,源自数据库上下文。这是我的模型的摘录。

[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/

相关文章:

c# - 如何将实时音频流传递到 Direct Line Speech 端点?

c# - 将 LINQ-to-SQL 谓词组合成单个谓词

.net - EF 4.1,代码优先 : Eager loading of cascading collections

c# - 如何首先使用代码在 Fluent API 中配置多个关系?

c# - EF6 Code First 从类库迁移导致空白 Up/Down

c# - Recaptcha 客户端验证的理想解决方案

c# - 在不使用 Where() 的情况下使用 GroupBy() 和 Timeout() 时出现 NotSupportedException

c# - 如何使用 Microsoft.Azure.ActiveDirectory.GraphClient 删除 AzureAD 中的用户管理器

c# - 在 Entity Framework 中动态创建 DbSet<T>?

c# - Entity Framework 不插入/更新某些列(但仍应映射列)