James
James

Reputation: 2610

How to define a 0..1 to many relationship in code-first

I'm reading ado.net team blog's articles these days, when I find how to create one to one relationship, one to many relationship and many to many relationship. But, is there a way to create 0..1 to many relationship?

class TestA
{
    public int id { get; set; }
    public string name { get; set; }
    [Timestamp]
    public byte[] stamp { get; set; }       
    public TestB TB { get; set; }
}

class TestB
{
    public int id { get; set; }
    public string name { get; set; }
    [Timestamp]
    public byte[] stamp { get; set; }
    public ICollection<TestA> TA { get; set; }
}

class myContext : DbContext
{
    public DbSet<TestA> players { get; set; }
    public DbSet<TestB> teams { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestB>().HasOptional<TestA>(a => a);
    }
}

Thx inadvance!

Upvotes: 0

Views: 1778

Answers (1)

Eranga
Eranga

Reputation: 32437

You are almost there. Try mapping it as follows.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestA>().HasOptional(a => a.TB)
       .WithMany(b => b.TA);
}

Articles on mapping

Upvotes: 1

Related Questions