最初にコードを使用している場合は、流暢なコードAPIを使用するか、属性を使用してモデルを改良することにより、永続性マッピングをカスタマイズできます。Idなどの単純なキー名を使用する場合、EFは推論を通じて関係を解決できます。あなたの場合、EFはPersonIDとAddressIDがキーであるというヒントを必要とします。
属性アプローチを使用するには、プロジェクトにSystem.ComponentModel.DataAnnotationsへの参照を追加し、対応する'usingSystem.ComponentModel.DataAnnotations;'を追加します。必要に応じてソースファイルに追加します。次のサンプル(EF 4.3.1)は、生成されたAddressesテーブルとPersonsテーブルの間に「1対多」の関係を生成します(この場合、1対1は必要ありません)。コードを実行すると、SQLServerデータベースダイアグラムウィンドウに関係が表示されます。
class Program
{
static void Main(string[] args)
{
using (ContactsEntities entities = new ContactsEntities())
{
Address doeaddress = new Address() { Street = "1 Broadway", ZipCode = "01234" };
Address doeaddress2 = new Address() { Street = "2 Broadway", ZipCode = "01234" };
entities.Addresses.Add(doeaddress);
entities.Persons.Add(new Person() { FirstName = "Jane", LastName = "Doe", Address = doeaddress });
entities.Persons.Add(new Person() { FirstName = "John", LastName = "Doe", Address = doeaddress });
entities.Persons.Add(new Person() { FirstName = "Jim", LastName = "Doe", Address = doeaddress2 });
entities.SaveChanges();
}
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
}
[Table("Addresses")]
public partial class Address
{
public Address()
{
this.Persons = new HashSet<Person>();
}
[Key]
public int AddressID { get; set; }
[Required]
public string Street { get; set; }
[RegularExpression(@"^(\d{5}-\d{4}|\d{5}|\d{9})$")]
[Required]
public string ZipCode { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
[Table("Persons")]
public partial class Person
{
[Key]
public int PersonID { get; set; }
public int AddressID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[ForeignKey("AddressID")]
public virtual Address Address { get; set; }
}
public partial class ContactsEntities : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<Person> Persons { get; set; }
}