8

If I have the following objects:

public class Application 
{
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
}

public class TestAccount
{
    public int TestAccountId { get; set; }
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual Application Application { get; set; }
}

EF Mapping looks like this:

modelBuilder.Entity<Application>()
    .HasMany(a => a.TestAccounts)
    .WithRequired(t => t.Application)
    .WillCascadeOnDelete(false);

The relationship between these two is that I can have applications with zero or many TestAccounts.

I am trying to describe a fk relationship between the two tables. Can someone explain what the ".WithRequired" does. I don't understand why this is needed.

1 Answers1

14

It means that each TestAccount entity MUST have an Application entity associated with it.I suppose one way to put it is like this:

If in your DB, you have a foreign key to another table and that foreign key is NOT NULL, then use WithRequired, else if it can be NULL, then use WithOptional

Here is some documentation worth looking at:

http://msdn.microsoft.com/en-us/data/jj591620.aspx

Matt
  • 6,787
  • 11
  • 65
  • 112