I have the the following situation:
- I have a few accounts and a few gametables.
- Each gametable has a creator.
- Each accounts can sit on a table (but doesn't have to).
My model classes look like this:
public class GameTable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id
{
get;
set;
}
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public Guid CreatorId { get; set; }
[ForeignKey(nameof(CreatorId))]
public Account Creator { get; set; }
}
public class Account
{
public Account()
{
Elo = 1000;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[MaxLength(15)]
[MinLength(4)]
public string Name { get; set; }
[Required]
[MaxLength(32)]
[MinLength(32)]
public string PasswordHash { get; set; }
public int Elo { get; set; }
public bool IsAdmin { get; set; }
public Guid? CurrentTableId { get; set; }
[ForeignKey(nameof(CurrentTableId))]
public virtual GameTable CurrentTable { get; set; }
}
My context is currently looking like this:
[Export(typeof(MyDbContext)), PartCreationPolicy(CreationPolicy.Shared)]
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
public MyDbContext() : base("DbContextCon")
{
Database.SetInitializer<PiksenDbContext>(new CreateDatabaseIfNotExists<PiksenDbContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<Account> Accounts { get; set; }
public virtual DbSet<SecurityToken> SecurityTokens { get; set; }
public virtual DbSet<GameTable> GameTables { get; set; }
}
Unfortunately it doesn't work with both foreign key set up like this. The following message is giving my some headache at the moment:
System.InvalidOperationException: 'Unable to determine the principal end of an association between the types 'namespace.GameTable' and 'namespace.Account'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.'
However, when I comment out one of the FK-Relationships, everything is fine. It seems like there is some sort of conflict between those two.
The result I am trying to get is one nullable FK in Account called CurrentTableId and a non-nullable FK in GameTable called CreatorId.