2014-07-02 13 views

Trả lời

11

Dưới đây là ví dụ cho thấy cách tạo khóa duy nhất kết hợp thông qua API thông thạo. Khóa tổng hợp bao gồm ProjectId và SectionOdKey.

public class Table 
{ 
    int Id{set;get;}  
    int ProjectId {set;get;} 
    string SectionOdKey{set;get;} 
} 

public class TableMap : EntityTypeConfiguration<Table> 
{ 
    this.Property(t => t.ProjectId).HasColumnName("ProjectId") 
       .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 1){IsUnique = true})); 
    this.Property(t => t.SectionOdKey).HasColumnName("SectionOdKey") 
       .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 2){IsUnique = true})); 
} 
13

Hãy nói rằng bạn có một thực thể có tên

public class MyTable 
{ 
    public int Id {get; set;} 
    public String Name {get; set;} 

} 

bạn có thể tạo khóa composit sử dụng

public class YourContext : DbContext 
{ 
    public DbSet<MyTable> MyTables { get; set; } 

    protected override void OnModelCreating(DbModelBuilder builder) 
    { 
     builder.Entity<MyTable>().HasKey(table => new {table.Id, table.Name}); 
    } 
} 

nếu bạn thích dữ liệu chú thích bạn có thể đơn giản thêm KeyAttribute với nhiều thuộc tính

public class MyTable 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // optional 
    [Key] 
    public int Id { get; set; } 

    [DatabaseGenerated(DatabaseGeneratedOption.None)] // optional 
    [Key] 
    public String Name { get; set; } 

} 
+0

Hey! Tôi chuẩn bị trả lời câu hỏi đó. –

+0

@ByteBlast ahh! gr8 2 bạn ở đây, một phần của ans vẫn còn thiếu, thêm độc đáo thông qua api thông thạo –

Các vấn đề liên quan