Как сначала создать составной первичный ключ в коде Entity Framework 4?
Сначала я получаю код EF4, и мне это нравится. Но мне трудно сопоставить сущность с таблицей с составным первичным ключом.
Проработанная конфигурация выглядит следующим образом:
public SubscriptionUserConfiguration()
{
Property(u => u.SubscriptionID).IsIdentity();
Property(u => u.UserName).IsIdentity();
}
Что вызывает это исключение:
Не удалось вывести ключ для типа сущности 'SubscriptionUser'.
Что мне не хватает?
Ответы
Ответ 1
Вы также можете использовать
HasKey(u => new { u.SubscriptionID, u.UserName });
Edit:
Одно ограничение, которое я обнаружил, заключается в следующем:
public ProjectAssignmentConfiguration()
{
HasKey(u => u.Employee.EmployeeId);
HasKey(u => u.Project.ProjectId);
}
или
public ProjectAssignmentConfiguration()
{
HasKey(u => new { u.Employee.EmployeeId, u.Project.ProjectId });
}
Итак, как вы настраиваете сущность, где в таблице соединений есть первичный ключ, состоящий из внешних ключей?
Ответ 2
Я попытаюсь объяснить это шаг за шагом, используя следующий Entity
public class Account
{
public int AccountId1 { get; set; }
public int AccountId2 { get; set; }
public string Description { get; set; }
}
-
Создайте класс, полученный из объекта EntityTypeConfiguaration<TEntity>
, чтобы переопределить соглашения
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
}
}
-
Создайте класс, полученный из объекта DbContext
Object, переопределите 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());
}
}
Надеюсь, это поможет вам!
Ответ 3
Вы также можете использовать атрибут Column
public class UserProfileRole
{
[Key, Column(Order = 0)]
public int UserId { get; set; }
[Key, Column(Order = 1)]
public int RoleId { get; set; }
}
Ответ 4
Решил: я должен использовать HasKey, а не Identity. Это работает:
public SubscriptionUserConfiguration()
{
HasKey(u => u.SubscriptionID);
HasKey(u => u.UserName);
}