很难知道你是在做代码优先还是数据库/模型优先。我将给出一个有效的代码优先答案(首先!)。对于 1-Many 和 Many-Many 关系,您可以使用注释、属性等来完成。但对于 1-1,我认为您也需要 fluent api。
“如何首先在 EF 4.1 代码中使用延迟加载和两个表上的相同主键来编写可选的一对一关系?”中也回答了这个问题?. 我相信,所需的流畅 API 比那个答案要短。
例如
public class ExampleContext : DbContext
{
public ExampleContext()
: base("Name=ExampleContext") {
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Location> Locations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOptional(m => m.Location)
.WithRequired();
}
}
public class Employee
{
[Key]
[Column("employee_id")]
public int EmployeeId { get; set; }
public virtual Location Location { get; set; }
}
public class Location
{
[Key]
[Column("employee_id")]
public int EmployeeId { get; set; }
}
编辑请注意,此示例中不需要 [Key] 属性来创建迁移工作,它们只是很好地传达意图。这是一个很好的参考,更详细地讨论了共享主键关联
// Migration class as follows was generated by code-first migrations (add-migration OneToOne) and then updated the database by update-database
public partial class OneToOne : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Employees",
c => new
{
employee_id = c.Int(nullable: false, identity: true),
})
.PrimaryKey(t => t.employee_id);
CreateTable(
"dbo.Locations",
c => new
{
employee_id = c.Int(nullable: false),
})
.PrimaryKey(t => t.employee_id)
.ForeignKey("dbo.Employees", t => t.employee_id)
.Index(t => t.employee_id);
}
public override void Down()
{
DropIndex("dbo.Locations", new[] { "employee_id" });
DropForeignKey("dbo.Locations", "employee_id", "dbo.Employees");
DropTable("dbo.Locations");
DropTable("dbo.Employees");
}
}
使用示例:
using (ExampleContext db = new ExampleContext())
{
var newEmployee = db.Employees.Add(new Employee() { /* insert properties here */ });
db.SaveChanges();
db.Locations.Add(new Location() { EmployeeId = newEmployee.EmployeeId /* insert properties here */ });
db.SaveChanges();
var employee1 = db.Employees.First();
var employee1Location = employee1.Location;
}