這是很難知道,如果你正在做的代碼的第一或數據庫/模型第一。我會給出一個有效的代碼優先答案(第一!)。對於一對多和多對多的關係,你可以用註釋,屬性等來完成。但對於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