Mapping 实体框架代码优先:共享主键

Mapping 实体框架代码优先:共享主键,mapping,ef-code-first,code-first,entity-framework-4.1,Mapping,Ef Code First,Code First,Entity Framework 4.1,我有一个主键超过3列(1个varchar和2个integer)的现有表。 我如何告诉实体框架使用这个“键”。 是否可以使用modelBuilder、属性或其他方法 谢谢 在fluent api中,必须使用匿名类型: modelBuilder.Entity<YourType>() .HasKey(e => new { e.VarChar, e.

我有一个主键超过3列(1个varchar和2个integer)的现有表。 我如何告诉实体框架使用这个“键”。 是否可以使用modelBuilder、属性或其他方法


谢谢

在fluent api中,必须使用匿名类型:

modelBuilder.Entity<YourType>()
            .HasKey(e => new 
                {
                    e.VarChar,
                    e.Int1,
                    e.Int2
                });
在这两种情况下,列的顺序都很重要。一旦您尝试使用
DbSet.Find
,您将必须以相同的顺序提供密钥。EF在内部也使用order

public class YourType
{
    [Key, Column(Order = 0)]
    public string VarChar { get; set; }
    [Key, Column(Order = 1)]
    public int Int1 { get; set; }
    [Key, Column(Order = 2)]
    public int Int2 { get; set; }
}