the solution below if for EF Code First 4.1, it shows how to design the two classes in order to have a relationshiop one-to-zero/one, the result will be:
- Throne{Id(PK), Name..}
- King {Id(PK,FK), Name..}
public class Throne
{
public int Id { get; set; }
public string Name { get; set; }
public virtual King King { get; set; }
}
public class King
{
public int Id { get; set; }
public virtual Throne Throne { get; set; }
public string Name { get; set; }
}
The relationship is then defined in the OnModelCreating of the context or in a configuration class:
public class MyContext : DbContext
{
public DbSet< Throne> Thrones { get; set; }
public DbSet< King> Kings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//We define the key for the King table
modelBuilder.Entity< King>().HasRequired(x => x.Throne);
}
}
You can then:
var throne = new Throne(){Name = "First Throne"};
var king = new King() { Name = "First King" };
throne.King = king;
context.Thrones.Add(throne);
context.SaveChanges();