0

I have a scenario I'm getting a little muddled with using EF code first. The classes I've created are below:

public class Company
{
    public int Id { get; set; }
    public List<Contact> Contacts { get; set; }
    public List<Job> Jobs { get; set; }
}

public class Contact
{
    public int Id { get; set; }
    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }
    public int CompanyId { get; set; }       
    public List<Job> Jobs { get; set; }
}

public class Job
{
    public int Id { get; set; }
    [ForeignKey("CompanyContactId")]
    public virtual CompanyContact CompanyContact { get; set; }
    public int CompanyContactId { get; set; }
    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }
    public int CompanyId { get; set; } 
}    

However, when I build the DB I get the following error:

Introducing FOREIGN KEY constraint 'FK_Contacts_Company_CompanyId' on table 'Contacts' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

So a little research indicates the answer to this is to use the Fluent API to define the mappings as required but I can't get my head around how to do this or find an example of a similar scenario.

I realise I could remove the Company class from Job and navigate through Contact but I'd prefer not to if possible.

Any help gratefully received

ledragon
  • 299
  • 6
  • 17
  • There are plenty of articles on fluent API usage – Eranga Jul 15 '12 at 12:31
  • *So a little research* - the proper statement would be no research because simply putting *Entity framework "cause cycles or multiple cascade paths"* to Google will provide you answer with sample (including [this one](http://stackoverflow.com/questions/5828394/entity-framework-4-1-inverseproperty-attribute-and-foreignkey)). So what fluent mapping doesn't work for you? – Ladislav Mrnka Jul 16 '12 at 09:27
  • Nope...I saw that one (and many others). As mentioned above I'm struggling with understanding how to construct the fluent mapping as the thread you've posted suggests. Sorry if my lack of understanding offends you! – ledragon Jul 16 '12 at 15:17

1 Answers1

0

You want to use the EF model builder to set up these relationships.

An example of how you would do this for one of your properties would be the following:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>().HasOptional(e => e.Company).WithMany(c=>c.Contacts);
    } 

For more of an explanation around how to use the modelbuilder take a look at my article on EF Navigation Properties

undefined
  • 33,537
  • 22
  • 129
  • 198