これが私がこれを解決する方法です。
クラスに外部キー プロパティを追加します。と について話しParentAccountId
ていAccountOwnerId
ます。操作を簡単にするために、子アカウントのコレクションを Account に追加し、所有アカウントのコレクションを Contact に追加しました。「通常の」プロパティを仮想にする必要はないことに注意してください。ナビゲーション プロパティのみを仮想化する必要があります。
public class Account
{
public int AccountID {get; set;}
public string AccountName {get; set;}
public int? ParentAccountId { get; set; }
public int? AccountOwnerId { get; set; }
public virtual Account ParentAccount { get; set; }
public virtual ICollection<Account> ChildAccounts { get; set; }
public virtual Contact AccountOwner { get; set; }
public Account()
{
ChildAccounts = new List<Account>();
}
}
public class Contact
{
public int ContactID { get; set; }
public string ContactName { get; set; }
public virtual ICollection<Account> OwnedAccounts { get; set; }
public Contact()
{
OwnedAccounts = new List<Account>();
}
}
次に、Account クラスのマッピングを作成して、リレーションシップのセットアップ方法を EF に説明します。
public class AccountMapping : EntityTypeConfiguration<Account>
{
public AccountMapping()
{
HasOptional(x => x.ParentAccount).WithMany(x => x.ChildAccounts).HasForeignKey(x => x.ParentAccountId);
HasOptional(x => x.AccountOwner).WithMany(x => x.OwnedAccounts).HasForeignKey(x => x.AccountOwnerId);
}
}
最後に、マッピングを DbContext クラスに追加します。
public MyContext : DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AccountMapping());
}
}
AccountOwner と ParentAccount はオプションであると想定していることに注意してください。必要な場合は、外部プロパティのタイプを からint?
にint
変更HasOptional
し、マッピングの を に変更しHasRequired
ます。