如何首先在Entity Framework 4代码中映射复合主键?

composite-key entity-framework orm

我首先要掌握EF4代码,并且喜欢它到目前为止。但是我无法将实体映射到具有复合主键的表。

我试过的配置看起来像这样:

public SubscriptionUserConfiguration()

    {
                Property(u => u.SubscriptionID).IsIdentity();
                Property(u => u.UserName).IsIdentity();
    }

抛出此异常:无法推断实体类型“SubscriptionUser”的密钥。

我错过了什么?

一般承认的答案

你也可以用

HasKey(u => new { u.SubscriptionID, u.UserName });

编辑:

我发现的一个限制是以下不起作用:

public ProjectAssignmentConfiguration()
{
    HasKey(u => u.Employee.EmployeeId);
    HasKey(u => u.Project.ProjectId);
}

要么

public ProjectAssignmentConfiguration()
{
    HasKey(u => new { u.Employee.EmployeeId, u.Project.ProjectId });
}

那么如何设置一个实体,其中连接表有一个由外键组成的主键?


热门答案

我将尝试使用以下实体逐步解释它

public class Account
{
    public int AccountId1 { get; set; }
    public int AccountId2 { get; set; }
    public string Description { get; set; }
}
  1. 创建一个派生自EntityTypeConfiguaration<TEntity> Object的类以覆盖约定

    class AccountEntityTypeConfiguration : EntityTypeConfiguration<Account>
    {
    
        public AccountEntityTypeConfiguration()
        {
          // The Key
          // The description of the HasKey Method says
          // A lambda expression representing the property to be used as the primary key.
          // If the primary key is made up of multiple properties then specify an anonymous type including the properties.
          // Example C#: k => new { k.Id1, k.Id2 }
          // Example VB: Function(k) New From { k.Id1, k.Id2 }
          this.HasKey(k => new { k.AccountId1, k.AccountId2 } );  // The Key
    
          // Maybe the key properties are not sequenced and you want to override the conventions
          this.Property(p => p.AccountId1).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
          this.Property(p => p.AccountId2).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
    
          this.Property(p => p.Description).IsRequired();  // This property will be required
          this.ToTable("Account");  // Map the entity to the table Account on the database
        }
    }
    
  2. 当创建从派生类DbContext对象,覆盖OnModelCreating方法,并添加一个新的AccountEntityTypeConfiguration对象模型生成器的配置。

    public class MyModelAccount : DbContext
    {
        public DbSet<Account> Accounts { get; set;}
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Add a new AccountEntityTypeConfiguration object to the configuration of the model, that will be applied once the model is created. 
            modelBuilder.Configurations.Add(new AccountEntityTypeConfiguration());
        }
    
    }
    

希望它能帮到你!



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因