实体框架关系问题

时间:2013-03-06 19:11:52

标签: entity-framework relationship

我有以下模型:

public class Employee
    {
        public int ID { get; set; }
        public string name { get; set; }
        public int LocationID { set; get; }

        public virtual Location Location { set; get; }

    }
    public class Location {

        public int ID { set; get; }
        public string NAME { set; get; }
        public virtual ICollection<Employee> LocationEmployees { get; set; }

    }

基本上,员工属于某个地点,而且某个地点拥有大量员工。我想在名为location contact的位置模型中添加一列,该列将是一个员工ID。我尝试通过代码优先迁移添加它,但它没有产生预期的结果。

添加了列

public class Employee
    {
        public int ID { get; set; }
        public string name { get; set; }
        public int LocationID { set; get; }

        public virtual Location Location { set; get; }

    }
    public class Location {

        public int ID { set; get; }
        public string NAME { set; get; }

        public int EmployeeID { get; set; }

        public virtual Employee Employee { get; set; }
        public virtual ICollection<Employee> LocationEmployees { get; set; }

    }

生成了迁移文件:

public override void Up()
        {
            DropForeignKey("dbo.Employees", "LocationID", "dbo.Locations");
            DropIndex("dbo.Employees", new[] { "LocationID" });
            RenameColumn(table: "dbo.Employees", name: "LocationID", newName: "Location_ID");
            AddColumn("dbo.Locations", "EmployeeID", c => c.Int(nullable: true));
            AddForeignKey("dbo.Employees", "Location_ID", "dbo.Locations", "ID");
            AddForeignKey("dbo.Employees", "LocationID", "dbo.Locations", "ID", cascadeDelete: false);
            AddForeignKey("dbo.Locations", "EmployeeID", "dbo.Employees", "ID", cascadeDelete: false);
            CreateIndex("dbo.Employees", "Location_ID");
            CreateIndex("dbo.Employees", "LocationID");
            CreateIndex("dbo.Locations", "EmployeeID");
        }

        public override void Down()
        {
            DropIndex("dbo.Locations", new[] { "EmployeeID" });
            DropIndex("dbo.Employees", new[] { "LocationID" });
            DropIndex("dbo.Employees", new[] { "Location_ID" });
            DropForeignKey("dbo.Locations", "EmployeeID", "dbo.Employees");
            DropForeignKey("dbo.Employees", "LocationID", "dbo.Locations");
            DropForeignKey("dbo.Employees", "Location_ID", "dbo.Locations");
            DropColumn("dbo.Locations", "EmployeeID");
            RenameColumn(table: "dbo.Employees", name: "Location_ID", newName: "LocationID");
            CreateIndex("dbo.Employees", "LocationID");
            AddForeignKey("dbo.Employees", "LocationID", "dbo.Locations", "ID", cascadeDelete: false);
        }

我收到此错误:

System.Data.SqlClient.SqlException (0x80131904): Foreign key 'FK_dbo.Employees_dbo.Locations_LocationID' references invalid column 'LocationID' in referencing table 'Employees'.
Could not create constraint. See previous errors.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
Foreign key 'FK_dbo.Employees_dbo.Locations_LocationID' references invalid column 'LocationID' in referencing table 'Employees'.
Could not create constraint. See previous errors.

我错过了什么?

1 个答案:

答案 0 :(得分:2)

我不确切地知道为什么迁移会引发此异常,但很明显它不会创建您想要的关系。当添加三个外键而不是两个时,您可以在Up方法中看到它。 EF在此处创建三个关系,其中一个具有默认的FK名称Location_ID

原因是EF不知道Employee.Location是否有Location.EmployeeLocation.LocationEmployees作为反向导航属性。

您必须使用数据注释明确定义...

public class Employee
{
    //...

    [InverseProperty("LocationEmployees")]
    public virtual Location Location { set; get; }
}

...或使用Fluent API:

modelBuilder.Entity<Location>()
    .HasMany(l => l.LocationEmployees)
    .WithRequired(e => e.Location)
    .HasForeignKey(e => e.LocationID);

modelBuilder.Entity<Location>()
    .HasOptional(l => l.Employee)
    .WithMany()
    .HasForeignKey(l => l.EmployeeID);

请注意,我在第二个关系中使用了HasOptional而不是HasRequired,这意味着您还必须使Location模型中的FK可以为空:

public int? EmployeeID { get; set; }

由于没有有效的排序EmployeeLocation实体可以插入到数据库中,因为它们彼此相互依赖,所以不能要求这两种关系。

或者,如果符合您的业务要求,您也可以在int? LocationID Employee中与{{1}}建立其他关系。