What role does .WithRequired play in the EF Fluent API?

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; } } 

The EF mapping is as follows:

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

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

I am trying to describe fk relationship between two tables. Can someone explain what ".WithRequired" does. I do not understand why this is necessary.

+4
source share
1 answer

This means that every TestAccount object MUST have an Application object associated with it. I believe one way to do this is as follows:

If in your database you have a foreign key for another table, and the foreign key is NOT, then use WithRequired , otherwise, if it can be NULL, then use WithOptional

Here are a few documents to watch:

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

+8
source

All Articles