Question

I have a legacy table I need to connect my app to. I am using a code-first, POCO model. I have the following classes:

public class Equipment
{
    [Key]
    public string EquipmentId { get; set; }
    public string OriginatorId { get; set; }

    public virtual Employee Employee { get; set; }
}

public class Employee
{
    [Key]
    [Column("employee_id")]
    public string EmployeeId { get; set; }

    public string EmployeeName { get; set; }

    [ForeignKey("OriginatorEmployeeId")]
    public virtual Equipment Equipment { get; set; }
}

I need to map EmployeeId in the Employee class to to OriginatorEmployeeId in the Equipment class.

Also, the legacy table is represented by the Employee class. The table is actually named employee (lower case) and the EmployeeId column is named "employee_id". I want to keep naming of my classes and properties consistent with the rest of the app, hence Employee and EmployeeId.

Here is what I have tried using fluent API:

    modelBuilder.Entity<Employee>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("employee");
    });

    modelBuilder.Entity<Equipment>()
                .HasOptional<Employee>(u => u.Employee)
                .WithOptionalDependent(c => c.Equipment).Map(p => p.MapKey("OriginatorEmployeeId"));

I am probably mixing things I don't need to. The error I am getting right now is:

Multiplicity is not valid in Role 'Equipment_Employee_Source' in relationship 'Equipment_Employee'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

Any help is appreciated.

Was it helpful?

Solution

Can an employee record be associated to more than one equipment record? If they can then your Employee POCO should contain a collection property representing a one-to-many relationship between Employee and Equipment.

public virtual ICollection<Equipment> Equipments {get;set;}

You configuration should then be adjusted accordingly to show this relationship:

modelBuilder.Entity<Employee>()
            .HasMany<Equipment>(u => u.Equipments)
            .WithRequired(c => c.Employee).HasForeignKey(p => p.OriginatorId);

It also looks like you will need to setup a configuration for your column name mappings as well. Therefore, I would recommend that you create a separate configuration file for each of your POCOs to make it easier to manage the configurations, then just add those configurations to the modelbuilder.Configurations collection in your OnModelCreating event of your DBContext

public class EmployeeConfiguration : EntityTypeConfiguration<Employee>

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelbuilder.Configurations.Add(new EmployeeConfiguration());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top