Baral
Baral

Reputation: 3141

EF 4.0 - CodeFirst One To Many - Fluent API

I have the following two classes:

public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
}


public class Trip
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IEnumerable<Person> Persons { get; set; }
}

As you can see, a Trip can have 1 or more Persons...

I tried to use the EntityConfiguration to build the database properly but I cannot manage to make it work... I am quite confused on its usage:

public class TripConfiguration : EntityTypeConfiguration<Trip>
{
    internal TripConfiguration()
    {
        // ???

    }
}

What do I need to write to have the application to behave properly:

  1. I need at least one person.
  2. I might have more that one person
  3. A person cannot be in the SAME trip twice
  4. A person can be in more than one trip

Upvotes: 0

Views: 47

Answers (2)

Arturo Martinez
Arturo Martinez

Reputation: 2583

This is not a One-To-Many relationship, this is a Many-To-Many relationship, you need to have collections on both sides of the relationship. EF will create the joiner table on your behalf. Since today you cannot configure a person being in a trip only once you will need to create a unique constraint in your joiner table once is created to assure this happens since EF does not yet support Unique Key constraints through configuration.

public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public virtual ICollection<Trip> Trips { get; set; }
}


public class Trip
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
}

then

class PersonConfiguration : EntityTypeConfiguration<Person>
{
    public PersonConfiguration()
    {
         this.HasMany(t => t.Trips).WithMany(t => t.Persons);
    }
}

Upvotes: 0

Loetn
Loetn

Reputation: 4030

Try this:

        this.HasRequired(x => x.Person)
            .WithMany(x => x.Trips)
            .HasForeignKey(x => x.PersonId);

Your classes:

public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public virtual ICollection<Trip> Trips { get; set;}
}


public class Trip
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PersonId { get; set; }
    public virtual Person Person { get; set; }
}

And as far that I know, EF doesn't support unique FK (or correct me if I'm wrong..). So you have to check it yourself.

Upvotes: 1

Related Questions