0

I'll try create one-to-one relation using EF and Fluent API.

First class:

public class Game
{
    public int Id { get; set; }
    public Guid Token { get; set; }
    public string Player { get; set; }
    public virtual Field Field { get; set; }
    public virtual ICollection<Move> Moves { get; set; }
    public GameStatus Status { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public PlayerCode Winner { get; set; }

    public Game()
    {
        Status = GameStatus.NoteDone;
        StartTime = DateTime.UtcNow;
        Winner = PlayerCode.None;
        Field = new Field {Game = this};
        Token = Guid.NewGuid();
    }
}

Secong class:

public class Field : IEntity
{
    public int Id { get; set; }
    public virtual Game Game { get; set; }
    public string CellsString { get; set; }
}

And configure relations in context

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Game>()
        .HasRequired<Field>(g => g.Field)
        .WithRequiredDependent(f => f.Game);
    base.OnModelCreating(modelBuilder);
}

But after this relation in DB is not created. Tables look like this

Created tables

I try many variations of Fluent configuration, but no one works for me. Where i do mistake?

beta-tank
  • 390
  • 1
  • 4
  • 17
  • I've had the issue before where in a 1-1 required relationship, it uses the Primary Key of the table as the Foreign Key as well. Have you checked the actual constraints on the tables, not just the columns? – Vlad274 Oct 14 '15 at 18:56
  • @Vlad274 thanks, I check my constraints and see that EF use PK as FK – beta-tank Oct 15 '15 at 04:33

1 Answers1

1

You can specify a mapping for foreign key if you don't wish to add it as a property to your entity class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Game>()
        .HasRequired(g => g.Field)
        .WithRequiredPrincipal(f => f.Game)
        .Map(m => m.MapKey("GameId"));
}

You probably meant WithRequiredPrincipal, not WithRequiredDependent since you probably want that foreign key to be in the Field table.

Uber Bot
  • 511
  • 3
  • 8