代码之家  ›  专栏  ›  技术社区  ›  server info

EF代码优先-复合密钥

  •  3
  • server info  · 技术社区  · 16 年前

        public class Product
    { 
    public string ProductID {get;set;}
    public string ShortDescription {get;set;}
    public string UserName {get;set;}
    }
    

    modelBinder.Entity<Product>().
    HasKey(p=>p.ProductID)
    .MapSingle(product =>
    new {
     colShotDesc = product.ShortDescription,
     colUser = product.UserName
    }
    ).ToTable("Products");
    

    我需要的是 ProductID=ShortDescription+映射中的用户名。。。 因为这两个合谋共享一个唯一的密钥约束。。。

    不知道这是否合理,但任何建议都会很好。。。 因为看起来db没有定义pk,只有唯一的键约束。。。

    帮个忙太好了。。

    2 回复  |  直到 16 年前
        1
  •  11
  •   Kevin LaBranche    15 年前

    听起来您想要一个复杂类型,并希望通过使用在属性名称末尾附加ID的约定将复杂类型识别为键。

    EF CF目前无法做到这一点。

    您可以通过key属性或FluentAPI告诉EF CF关于复合键的信息。

    public class Product 
    {  
      [Key, Column(Order=0)]
      public string ShortDescription {get;set;} 
      [Key, Column(Order=1)]
      public string UserName {get;set;} 
    }
    

    Fluent API:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Product>()
                   .HasKey(p=> new{p.ShortDescription, p.UserName});
    }
    

    您可以创建一个复杂类型,可以在代码中使用该类型,以便按照您希望代码在概念上的工作方式进行更多的工作。

    public class Product 
    {  
      public ProductID Key {get;set;}
    }
    
    public class ProductID 
    {
      public string ShortDescription {get;set;} 
      public string UserName {get;set;} 
    }
    

    然后使用Fluent API对其进行映射:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.ComplexType<ProductID>()
                   .Property(p=>p.ShortDescription)
                   .HasColumnName("ShortDescription")
                   .Property(p=>p.UserName)
                   .HasColumnName("UserName");
    }
    

    或者,如果要使用数据批注:

    [ComplexType]
    public class ProductID
    {
      [Column("ShortDescription")]
      public string ShortDescription {get;set;} 
      [Column("UserName")]
      public string UserName {get;set;} 
    }
    

    您必须指定列名,否则配置将假定列名为ProductID\u ShortDescription。。。。

    Here's some more info on Complex Types.

        2
  •  0
  •   Devart    16 年前

    实际上,您希望将单个概念属性映射到两个存储列。 有一段代码可以将列中的值连接到属性中,到目前为止还不错。