这是很难知道,如果你正在做的代码的第一或数据库/模型第一。我会给出一个有效的代码优先答案(第一!)。对于一对多和多对多的关系,你可以用注释,属性等来完成。但对于1-1我认为你也需要流利的API。
这也在"How do I code an optional one-to-one relationship in EF 4.1 code first with lazy loading and the same primary key on both tables?"回答。我相信,流畅的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; }
}
编辑注[关键]属性没有这个样本来创建迁移工作需要,他们只是很好的传达意图。这是一个很好的参考,在更详细地谈论使用Shared Primary Key Associations
// 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;
}
您是否使用代码优先的方法? –
模型更改后,您是否对数据库执行了EF迁移? – jure
@JoshC。是代码第一 – loyalflow