如何在实体框架中映射1:1(可选)映射

本文关键字:映射 可选 实体 框架 | 更新日期: 2023-09-27 18:13:26

我有一个类:

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'.

如何在实体框架中映射1:1(可选)映射

您是否尝试过显式指定FK/Navigation属性?

public int LocationId { get; set; }
[ForeignKey("LocationId")]
public virtual Location Location { get; set; }

当只填充相关对象的ID时,

Navigation属性未加载

很难知道您是在做代码优先还是数据库/模型优先。我将给出一个工作代码优先的答案(第一!)。对于1-多和多-多关系,你可以通过注释、属性等来实现。但是对于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; }
}

EDIT注意,在这个示例中,创建迁移工作不需要[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;
}