简体   繁体   English

遗留数据库上的实体框架代码第一个复合外键

[英]Entity Framework Code First Composite Foreign Key on legacy DB

So, I've been banging my head for a few days now and searching has led me nowhere close to a solution. 因此,几天来我一直在for头,搜索使我无处可寻。

I have a legacy database thats far from following EF's code convention and I'm using EF Code First. 我有一个遗留数据库,远没有遵循EF的代码约定,而我使用的是EF Code First。

This is my actual situation: (Irrelevant fields ommited for the sake of brevity) 这是我的实际情况:(为简洁起见,省略了Irlelevant字段)

[Table("PEDIDO")]
public class Pedido : IValidatableObject
{
    [Key, Column(Order = 1), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CODIGO { get; set; }

    [Key, Column(Order = 2), ForeignKey("DadosCliente"), Required]
    public int CLIENTE { get; set; }
    public virtual Cliente DadosCliente { get; set; }

    public virtual ICollection<MaterialPedido> DadosMateriaisPedido { get; set; }

}


[Table("MATERIAL_PEDIDO")]
public class MaterialPedido : IValidatableObject
{
    [Key, Required, Column(Order = 1)]
    public int NRPEDIDO { get; set; } // This column relates to Pedido.CODIGO

    [Key, Required, Column(Order = 2), ForeignKey("DadosCliente")]
    public int CLIENTE { get; set; }
    public virtual Cliente DadosCliente { get; set; }

    [Key, Required, Column(Order = 3)]
    public string CODIGO { get; set; }
    // Please note that this column is some sort of "virtual field". Its value should be hard-coded to "P" when relating to the table "PEDIDO"
}

public class EntitiesContext : DbContext
{
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Pedido>()
            .HasKey(p => new { p.CLIENTE, p.CODIGO })
            .HasMany(x => x.DadosMateriaisPedido)
            .WithOptional(p => p.Pedido)
            .HasForeignKey(x => new { x.CLIENTE, x.NRPEDIDO })
            .WillCascadeOnDelete(false);
    }
}

As of now I'm getting the following error: 截至目前,我收到以下错误:

ProjetoPI.EF.Pedido_DadosMateriaisPedido: : Multiplicity conflicts with the referential constraint in Role 'Pedido_DadosMateriaisPedido_Source' in relationship 'Pedido_DadosMateriaisPedido'. ProjetoPI.EF.Pedido_DadosMateriaisPedido:多重性与关系“ Pedido_DadosMateriaisPedido”中角色“ Pedido_DadosMateriaisPedido_Source”中的引用约束冲突。 Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'. 因为从属角色中的所有属性都是不可为空的,所以主体角色的多重性必须为'1'。 Pedido_DadosMateriaisPedido_Target: : Multiplicity is not valid in Role 'Pedido_DadosMateriaisPedido_Target' in relationship 'Pedido_DadosMateriaisPedido'. Pedido_DadosMateriaisPedido_Target:多重性在关系“ Pedido_DadosMateriaisPedido”中的角色“ Pedido_DadosMateriaisPedido_Target”中无效。 Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'. 由于从属角色指的是关键属性,因此从属角色的多重性上限必须为“ 1”。

What am I missing?Any help will be greatly appreciated! 我缺少什么?我们将不胜感激!

So, I've finally found out what was happening so below is my solution for future reference and hoping it's able to help other desperate souls like me: 因此,我终于发现了所发生的事情,因此以下是我的解决方案,以供将来参考,并希望它能够帮助像我这样的其他绝望灵魂:

My mapping was entirely wrong. 我的映射是完全错误的。 MATERIAL_PEDIDO has no relationship with PEDIDO (not sure I agree with this design, but...) and Entity Framework does not approve the creation of relationships that do not exist on the database. MATERIAL_PEDIDO与PEDIDO没有关系(不确定我是否同意此设计,但是...),并且Entity Framework不批准创建数据库中不存在的关系。 There is a third table that, besides containing MaterialPedido's children, its the relationship between Pedido and MaterialPedido. 第三个表除了包含MaterialPedido的孩子之外,还包含Pedido和MaterialPedido之间的关系。

[I can't post images, so I won't be able to post the DB Model =(]. So I cleared all relationships and started remodeling from scratch. [我无法发布图像,因此无法发布数据库模型=(]。因此,我清除了所有关系,并从头开始进行了建模。

Here are my working relationships: 这是我的工作关系:

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

        modelBuilder.Entity<Pedido>()
            .HasKey(p => new { p.CLIENTE, p.CODIGO })
            .HasMany<DetalhePedido>(p => p.DetalhesPedido)
            .WithRequired(dp => dp.Pedido)
            .HasForeignKey(dp => new { dp.CLIENTE, dp.NRPEDIDO });

        modelBuilder.Entity<MaterialPedido>()
            .HasKey(mp => new { mp.NRPEDIDO, mp.CLIENTE, mp.CODIGO })
            .HasMany<DetalhePedido>(mp => mp.DetalhesPedido)
            .WithRequired(dp => dp.MaterialPedido)
            .HasForeignKey(dp => new { dp.NRPEDIDO, dp.CLIENTE, dp.MATERIAL });
    }

[Table("MATERIAL_PEDIDO")]
public class MaterialPedido : IValidatableObject
{
    [Key, Required, Column(Order = 1)]
    public int NRPEDIDO { get; set; }

    [Key, Required, Column(Order = 2), ForeignKey("DadosCliente")]
    public int CLIENTE { get; set; }
    public virtual Cliente DadosCliente { get; set; }

    [Key, Column(Order = 3)]
    public string CODIGO { get; set; }

    public virtual ICollection<DetalhePedido> DetalhesPedido { get; set; }

}

[Table("DETALHE_PEDIDO")]
public class DetalhePedido
{
    [Key, Column(Order = 1)]
    public int NRPEDIDO { get; set; }
    [Key, Column(Order = 2)]
    public int CLIENTE { get; set; }
    [Key, Column(Order = 3)]
    public string MATERIAL { get; set; }
    [Key, Column(Order = 4)]
    public string CODIGO { get; set; }

    public virtual Pedido Pedido { get; set; }
    public virtual MaterialPedido MaterialPedido { get; set; }
}

[Table("PEDIDO")]
public class Pedido : IValidatableObject
{
    [Key, Column(Order = 1), DisplayName("Cód Pedido"), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CODIGO { get; set; }

    [Key, Column(Order = 2), Required, CustomValidation(typeof(GranitoEntities), "NotZero")]
    public int CLIENTE { get; set; }
    [ForeignKey("CLIENTE")]
    public virtual Cliente DadosCliente { get; set; }

    public virtual ICollection<DetalhePedido> DetalhesPedido { get; set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM