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

时间:2013-05-14 18:56:14

标签: c# entity-framework asp.net-mvc-4 entity-framework-4

我有一个类:

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;}

我正在尝试添加一个可选属性(Lazy loaded),因此员工可能拥有或者有一个位置。

我现在加载mvc应用程序时出现错误:

System.Data.SqlClient.SqlException: Invalid column name 'Location_Id'.

2 个答案:

答案 0 :(得分:0)

您是否尝试过明确指定FK / Navigation属性?

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

Navigation Property not loading when only the ID of the related object is populated

答案 1 :(得分:0)

很难知道你是在做代码优先还是数据库/模型优先。我将给出一个有效的代码优先答案(第一个!)。对于1-Many和Many-Many关系,您可以使用注释,属性等来完成。但对于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比答案要短。

e.g。

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]属性来创建迁移工作,它们只是传达意图。这是一个很好的参考,可以更详细地讨论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;
}
相关问题