【发布时间】:2015-04-18 16:54:39
【问题描述】:
我的 MVC 应用程序中有两个实体,并使用 Entity Framework 6 Code First 方法填充了数据库。 Student 实体中有两个城市 id;其中一个用于 BirthCity,另一个用于 WorkingCity。当我如上所述定义外键时,迁移后会在 Student 表中创建一个名为 City_ID 的额外列。是否有错误或如何定义这些 FK?提前致谢。
学生:
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int BirthCityID { get; set; }
public int LivingCityID { get; set; }
[ForeignKey("BirthCityID")]
public virtual City BirthCity { get; set; }
[ForeignKey("LivingCityID")]
public virtual City LivingCity { get; set; }
}
城市:
public class City
{
public int ID { get; set; }
public string CityName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
【问题讨论】:
-
为了清晰起见,我简化了我的代码,但我的代码与此逻辑完全相同。另一方面,我已经尝试从头开始重新创建数据库 2-3 次,但现在我再次这样做,并在几分钟内通知您。
-
@ChrisPratt:这是我现在遵循的步骤:1)从我的项目中删除了迁移文件夹及其内容。 2)清理并重建解决方案中的所有项目。 3) 在包管理器控制台上启用迁移,然后添加 AutomaticMigrationsEnabled = true;和 AutomaticMigrationDataLossAllowed = true;到配置文件的构造函数。 4)添加迁移。 >>>
-
@ChrisPratt:但是在这一步之后,我再次观察到 Up 方法中有一个属性“City_ID = c.Int()”。但是,我在解决方案中进行了搜索,没有“City_ID”属性。那么,为什么这个未定义的属性被添加到项目中呢?提前致谢。
标签: asp.net-mvc entity-framework ef-code-first foreign-keys foreign-key-relationship