1
votes

As I'm trying to change code first app to fit a multi tenancy demads, I basically added additional key column to all tables(and creating composite primary key):

    [Key, Column(Order = 1)] 
    public int CompanyID { get; set; }


public class Worker
{
     [Key, Column(Order = 0)] 
    public  int WorkerID{ get; set; }
     [Key, Column(Order = 1)] 
    public int CompanyID { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual int ActivityId { get; set; }
    public virtual Activity SomeActivity { get; set; }

}

public class Activity
{
    [Key, Column(Order = 0)] 
    public int ActivityID { get; set; }
    [Key, Column(Order = 1)] 
    public int CompanyID { get; set; }

    [Required]
    [Display(Name = "Desc.")]
    public virtual string Description{ get; set; }
}

When EF tries to generate database I get the error :

*Foreign key constraint 'Activity_ActActivityt' from table Worker(CompanyID, ActivityId) to table Activity (ActivityID, CompanyID):: Insufficient mapping: Foreign key must be mapped to some AssociationSet or EntitySets participating in a foreign key association on the conceptual side.*

Could you show me how to map these two tables, taking in account that For each user an activity is to be chosen.

Thanks, tihi

1
Incidentally, I had this exact issue earlier on this afternoon. I'm not 100% certain (still haven't fixed the issue -- I stopped working on it) but I think you may need to include a navigation property. - Mike Bailey

1 Answers

2
votes

I believe that you will have to set the foreign key mappings explicitly using data annotations (instead of relying on the conventions), however I am not entirely sure if this will work since you have overlap of a FK with a PK. In theory it should, though :)

public class Worker
{
    [Key, Column(Order = 0)] 
    public  int WorkerID{ get; set; }
    [Key, Column(Order = 1)] 
    [ForeignKey("SomeActivity")]
    public int CompanyID { get; set; }

    [Required]
    public string Name { get; set; }

    [ForeignKey("SomeActivity")]
    public virtual int ActivityId { get; set; }
    public virtual Activity SomeActivity { get; set; }

}