Я использую C# и Entity Framework. Я хочу определить ключ для объекта SimulationParameter
как комбинацию из трех столбцов (Name, StudyId, SimulationId). Мне не нужен столбец идентификатора, так как комбинация этих трех элементов всегда будет уникальной.Ключ, определенный для нескольких столбцов
Моделирование параметров:
public class SimulationParameter : IAggregateRoot
{
public SimulationParameter()
{
}
public String SimulationId { get; set; }
public Guid StudyId { get; set; }
public Study Study { get; set; }
public String Name { get; set; }
public String Value { get; set; }
}
Моделирование параметров Mapping:
class SimulationParameterMap : EntityTypeConfiguration<SimulationParameter>
{
public SimulationParameterMap()
{
HasKey(e => new {SimulationId = e.SimulationId, Name = e.Name, StudyId = e.StudyId});
Property(e => e.SimulationId)
.IsRequired();
Property(e => e.Name)
.IsRequired();
Property(e => e.Value)
.IsRequired();
HasRequired(e => e.Study)
.WithMany(e => e.SimulationsParameters)
.HasForeignKey(s => s.StudyId);
ToTable("SimulationParameters");
}
}
Теперь, когда я пытаюсь создать модель, у меня есть следующее сообщение об ошибке:
EntityType 'SimulationParameter' has no key defined. Define the key for this EntityType.
SimulationParameters: EntityType: EntitySet 'SimulationParameters' is based on type 'SimulationParameter' that has no keys defined.
Я действительно невежественны о том, почему это не действует ...
Edit 1:
Основываясь на предположении, что я добавил атрибут [Key]
над полем в модели:
public class SimulationParameter : IAggregateRoot
{
public SimulationParameter()
{
}
[Key]
public String SimulationId { get; set; }
[Key]
public Guid StudyId { get; set; }
public Study Study { get; set; }
[Key]
public String Name { get; set; }
public String Value { get; set; }
}
И получил другую ошибку:
System.InvalidOperationException: Unable to determine composite primary key ordering for type 'SimulationParameter'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys.
Edit2
Я был в состоянии сделать его работу, выполнив следующие действия:
public class SimulationParameter : IAggregateRoot
{
public SimulationParameter()
{
}
[Key, Column(Order=1)]
public String SimulationId { get; set; }
[Key, Column(Order = 2)]
public Guid StudyId { get; set; }
public Study Study { get; set; }
[Key, Column(Order = 3)]
public String Name { get; set; }
public String Value { get; set; }
}
Это все еще странно, однако, что он не работает, используя свободно, я буду продолжать смотреть и держать вас в курсе ,
'SimulationParameter' является объектом какого класса? Можете ли вы опубликовать код для своего класса – Phani
Я обновил вопрос с помощью кода. – CoachNono
Что произойдет, если вы добавите '[Key]' над каждым из этих полей в модели? Вы уверены, что он признает ваш свободный код? Это должно работать – John