Question

I have just started to work with the Entity framework and have created my Repository and context class and interfaces and defined my POCO and I am now trying to understand how the conventions working but am having difficulties and thus far have been unable to do so.

I have the following 2 POCO classes:

Gameweek

public class Gameweek
{
    [Key][Required]
    public int GameweekID { get; set; }

    [Required]
    public DateTime StartDate { get; set; }

    [Required]
    public DateTime Deadline { get; set; }

    [Required]
    public int NumberFixtures { get; set; }

    public virtual ICollection<Fixture> Fixtures { get; set; }

    public virtual ICollection<Result> Results { get; set; }
}

Fixture

public class Fixture
{
    [Key][Required]
    public int FixtureID { get; set; }

    [Required]
    public int GameweekID { get; set; }

    [Required]
    public string HomeTeam { get; set; }

    [Required]
    public string AwayTeam { get; set; }

    public virtual Result Result { get; set; }
}

Result

public class Result
{
    [Key][Required]
    public int FixtureID { get; set; }

    [Required]
    public int HomeGoals { get; set; }

    [Required]
    public int AwayGoals { get; set; }
}

In my model a Gameweek could contain between 0-20 fixtures. Each fixture in the gameweek has one result.

Am I modelling this correctly with the classes and the following convetions:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove < PluralizingTableNameConvention>();

        //Table relationships defined here
        modelBuilder.Entity<Gameweek>()
            .HasMany(g => g.Fixtures);                  

        modelBuilder.Entity<Fixture>()
            .HasOptional(f => f.Result);                    

    }

Any tips would be greatly appreciated.

Was it helpful?

Solution

Apparently you want to have a one-to-one relationship between Fixture and Result (a Result entity cannot be shared between multiple Fixtures), right? In this case your mapping is not 100% correct. You need:

modelBuilder.Entity<Fixture>()
    .HasOptional(f => f.Result)
    .WithRequired();

If you don't add WithRequired EF conventions will assume a WithMany, i.e. a one-to-many instead of one-to-one relationship.

Speaking of conventions, you can actually remove modelBuilder.Entity<Gameweek>().HasMany(g => g.Fixtures);, all [Required] attributes and the [Key] attribute in Gameweek. Only the one-to-one mapping above and the [Key] attribute on Result.FixtureID is needed. Everything else will be mapped automatically based on conventions.

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