Question

I'm fairly new to Entity Framework and feel more in control using the Code-First pattern rather than DB-First.

I was wondering what is more preferred when it comes to programmatically setting up ForeignKey relations between the entities.

Is it better to declare a FK_ property in the class which relates to the another class or is it better to declare an IEnumerable<> property in the class that gets related to?

public class IRelateToAnotherClass
{
    ...
    public int FK_IGetRelatedToByAnotherClass_ID { get; set; }
}

or

public class IGetRelatedToByAnotherClass
{
    ...
    public IEnumerable<IRelateToAnotherClass> RelatedTo { get; set; }
}
Was it helpful?

Solution

It all depends on what type of relationships you want between your entities (one-to-one, one-to-many, many-to-many); but, yes, you should declare foreign key properties. Check out this site for some examples.

Here's a one-to-many for your two classes:

public class IRelateToAnotherClass
{
    public int Id { get; set; } // primary key
    public virtual ICollection<IGetRelatedToByAnotherClass> IGetRelatedToByAnotherClasses { get; set; }
}

public class IGetRelatedToByAnotherClass
{
    public int Id { get; set; } // primary key
    public int IRelateToAnotherClassId { get; set; } // foreign key
    public virtual IRelateToAnotherClass IRelateToAnotherClass { get; set; }
}

and with some Fluent API mapping:

modelBuilder.Entity<IGetRelatedToByAnotherClass>.HasRequired<IRelateToAnotherClass>(p => p.IRelateToAnotherClass).WithMany(p => p.IGetRelatedToByAnotherClasses).HasForeignKey(p => p.Id);

OTHER TIPS

If I understand what you're asking correctly, you'd want both. You want an int FK property and an object property to use as the navigation property.

The end result would look something like this:

public class Employee
{
    [Key]
    public int EmployeeID { get; set; }

    [ForeignKey("Store")]
    public int StoreNumber { get; set; }

    // Navigation Properties
    public virtual Store Store { get; set; }
}

public class Store
{
    [Key]
    public int StoreNumber { get; set; }

    // Navigation Properties   
    public virtual List<Employee> Employees { get; set; }
}


If you haven't already, take a look at navigation properties and lazy-loading. Note that EF is clever enough to figure out that an int StoreID property corresponds to an object Store property, but if they are named differently (such as without the ID suffix), you must use the [ForeignKey] annotation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top