如果您首先使用代码,则可以使用流畅的代码 API 或使用属性来优化模型来自定义持久性映射。如果您要使用简单的键名(例如 Id),EF 可以通过推理解决关系;在您的情况下,EF 需要提示 PersonID 和 AddressID 是键。
要使用属性方法,请在项目中添加对 System.ComponentModel.DataAnnotations 的引用以及相应的“使用 System.ComponentModel.DataAnnotations;” 根据需要在源文件中。以下示例 (EF 4.3.1) 将在生成的 Addresses 和 Persons 表之间生成“一对多”关系(在这种情况下您不需要一对一)。运行代码后,您将在 SQL Server 数据库图表窗口中看到关系。
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; }
}