首先将外键映射到EF代码中的非主代理键列

时间:2016-06-25 14:02:19

标签: c# entity-framework ef-code-first foreign-keys entity-framework-6

public class A    
{   
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int Aid { get; set; }    

    public virtual ICollection<B> B { get; set; }    
}


public class B
{    
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Bid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]           
    Public virtual string BName {get ; set}

    [Key]
    [Column(Order = 1)]
    [Required]      
    public virtual int Aid { get; set; }

    [ForeignKey("Aid")]
    public virtual  A A { get; set; }

    public virtual ICollection<C> C { get; set; }    
}


public class C
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Cid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]    
    Public virtual string CName {get ; set}    

    [Key]
    [Column(Order = 1)]
    [Required]          
    public virtual int Bid { get; set; }

     [ForeignKey("Bid")]
     public virtual  B B { get; set; } 
}

B和C之间的关系让我很烦恼。我不想在B类中包含BName作为外键

  

错误:从属角色和主要角色中的属性数   在关系约束中必须相同

我理解错误,但我只想通过Bid指向C类,如何在不打扰A和B之间的关系的情况下实现它。

2 个答案:

答案 0 :(得分:4)

据我所知,首先使用属性或流畅的api在EF代码中执行不可能

但我可以建议您稍微改造一下您的解决方案 - 不要在B(BName, Aid)上创建主键 - 将其设为唯一索引 - Entity Framework Code first mapping without foreign key

public class B
{    
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Bid { get; set; }

    [Index("IX_B_Name_Aid", 1, IsUnique = true)]
    [Required]           
    Public virtual string BName {get ; set}

    [Index("IX_B_Name_Aid", 2, IsUnique = true)]
    [Required]      
    public virtual int Aid { get; set; }

    [ForeignKey("Aid")]
    public virtual  A A { get; set; }

    public virtual ICollection<C> C { get; set; }    
}


public class C
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     
    public virtual int Cid { get; set; }

    [Key]
    [Column(Order = 0)]
    [Required]    
    Public virtual string CName {get ; set}    

    [Key]
    [Column(Order = 1)]
    [Required]          
    public virtual int Bid { get; set; }

    [ForeignKey("Bid")]
    public virtual  B B { get; set; } 
}

索引将为您提供与主键查询相同的性能优势(尽管在Bid列上支持主Unique Key constraints for multiple columns in Entity Framework索引需要一些额外开销)。

另外,建议阅读 - surrogate

答案 1 :(得分:0)

该问题被标记为EF6。但是,如果您找到此搜索EF Core。可以使用Alternate Keys

来自链接:

  

备用键可用作关系的目标。

const components = [ PersonnelComponent ];
/*
  ...
  Anything that can be injected into
*/
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  // For each component
  components.forEach(element => {
    // Get its resolved factory
    const factory = this.componentFactoryResolver.resolveComponentFactory(element);

    console.log('Factory:', factory);
    console.log('Selector:', factory.selector);
  });
}