0

For example I have 2 tables:

public class Entity1
{
    public decimal SodaId { get; set; }
    public virtual Entity2 Entity2 { get; set; } 
}

public class Entity2
{
    public decimal Id { get; set; }
    public string PopId { get; set; }
    public virtual ICollection<Entity1> Entity1 { get; set; }
}

1 & 2 have a one to many relationship. PopId is the foreign key to Entity1. In the database there is not FK relationship set up. And since the column names are different, EF does not automatically see the relationship.

I want to set up navigation properties for these two tables, but am having trouble figuring out how to do so? I would like to do so using Fluent API and code first. Any help is greatly appreciated.

lgp8766
  • 1
  • 1
  • 2
  • Can I ask why wouldn't you have the FK relationship set up if you are using entity? – Zach M. Aug 11 '15 at 20:02
  • 3
    It's an existing database that I do not control. Many of the tables I will be working with have relationships, but no foreign key constraints. The column naming conventions don't always match either from table to table. – lgp8766 Aug 12 '15 at 13:10
  • 1
    You might want to check this article: [Click here](http://stackoverflow.com/questions/4465855/entity-framework-add-navigation-property-manually) – Ebbelink Aug 19 '15 at 08:04

1 Answers1

0

In your table you saying Entity 2 can have several Entity 1

public class Entity1
    {
        public decimal SodaId { get; set; }
        [ForeignKey("Entity2")]
        public int Id { get; set; }
        public virtual Entity2 Entity2 { get; set; }
    }


public class Entity2
    {
        public int Id { get; set; }
        public string PopId { get; set; }
        public virtual ICollection<Entity1> Entity1 { get; set; }
    }

This should work fine...

Ife Ologbese
  • 27
  • 1
  • 8
  • Can I ask why you added the int Id to Entity 1? The problem is that I don't actually have a foreign key in the database for these two tables and for many tables I will be working with. These two tables are related though. SodaId is the primary key of 1 and PopId acts as the foreign key of 2 even though there's no constraint in the DB. I do understand thought that my collection should be on the many side thanks for that. Thanks for your response. – lgp8766 Aug 12 '15 at 13:09