0

I have a class called Team, that can have any number of optional TeamMembers.

There appears to be 4 ways to declare it using EF / LINQ to Entities.

If the team class declares a List property, the TeamMember class can declare:

  1. Nothing

  2. The TeamID as an int property

  3. The Team as a object property

  4. Both TeamID and Team properties

What is the difference in the following declarations? Why would / should I choose one over another?

I understand that if I don't specify a Team / ID property, then I won't be able to access that from a TeamMember object. But beyond that how does it affect the DB relationships?

Class Team 
{
    List<TeamMember> TeamMembers {get;set;}
    ....
}

// implementation 1
Class TeamMember
{
    string Name {get;set;}
    ...
}

// implementation 2
Class TeamMember
{
    Team Team {get;set;}
    string Name {get;set;}
    ...
}

// implementation 3
Class TeamMember
{
    int TeamID {get;set;}
    string Name {get;set;}
    ...
}

// implementation 4
Class TeamMember
{
    Team Team {get;set;}
    int TeamID {get;set;}
    string Name {get;set;}
    ...
}
Martin Hansen Lennox
  • 2,837
  • 2
  • 23
  • 64

1 Answers1

1

The first 2 implementations will result in the same database structure.

enter image description here

Note the structure of the FK in TeamMembers. Entity Framework has seen there is a navigation property on Team called TeamMembers. EF has not found a Foreign Key specified but knows it needs to add one so does so in the format Class_PrimaryKey. Also note FK is nullable (optional). CASCADE DELETE is set to NO ACTION

The 3rd and 4th implementation result in a different database structure

enter image description here

Note FK is now non nullable ie Required and you will get constraint errors if Member doesn't have a Team associated with it. Also CASCADE DELETE is now enabled due to the Required FK (TeamId). You can use implementation 4 and have an optional Team when adding a new TeamMember. Use FluentApi to describe the relationship something like the following which will be added to your DbContext class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Member>()
                    .HasOptional(m => m.Team)
                    .WithMany(t => t.Members)
                    .HasForeignKey(m => m.TeamId)
                    .WillCascadeOnDelete(false);            
}

Hope that helps. NB Sorry for confusion just realised Ive used Member instead of TeamMember throughout this answer

SWilko
  • 3,542
  • 1
  • 16
  • 26
  • That is insanely helpful, thank you so much :) Plus it makes me feel lazy for not starting up a new project and trying it out myself. I hadn't realised it was that straightforward. – Martin Hansen Lennox Mar 06 '15 at 17:13