Dot-Net

.WithRequired 在 EF Fluent API 中起什麼作用?

  • March 6, 2013

如果我有以下對象:

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 映射如下所示:

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

這兩者之間的關係是我可以擁有零個或多個 TestAccounts 的應用程序。

我試圖描述兩個表之間的 fk 關係。有人可以解釋“.WithRequired”的作用。我不明白為什麼需要這樣做。

這意味著每個TestAccount實體必須有一個Application與之關聯的實體。我想一種說法是這樣的:

如果在您的數據庫中,您有另一個表的外鍵並且該外鍵不是 NULL,則使用WithRequired,否則如果它可以為 NULL,則使用WithOptional

以下是一些值得一看的文件:

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

引用自:https://stackoverflow.com/questions/15239488