[英]How to map a 1:1 (optional) mapping in Entity Framework
我有一个像这样的课程:
public class Employee
{
[Column("employee_id")]
public int EmployeId {get;set;}
}
public class Location
{
[Column("employee_location_id")]
public int Id {get;set;}
[Column("employee_id")]
public int EmployeeId {get;set;}
}
在Employee类上,我添加了一个虚拟属性:
public virtual Location Location {get;set;}
我试图添加一个可选属性(延迟加载),因此某个员工可能具有或或1个位置。
我现在在加载mvc应用程序时遇到错误:
System.Data.SqlClient.SqlException: Invalid column name 'Location_Id'.
您是否尝试过明确指定FK / Navigation属性?
public int LocationId { get; set; }
[ForeignKey("LocationId")]
public virtual Location Location { get; set; }
很难知道您是先执行代码还是先执行数据库/模型。 我将给出一个工作代码优先的答案(第一!)。 对于一对多和多对多关系,您可以使用批注,属性等来实现。但是对于1-1,我认为您也需要流利的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.