我在我的MVC应用程序中有两个实体,我用Entity Framework 6 Code First方法填充数据库。学生实体有两个城市编号;其中一个为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; } }
解决方法
要实现你想要的,你需要提供一些有用的配置.Code第一个约定可以识别双向关系,但不是当有
两个实体之间的多重双向关系。您可以添加配置(使用数据注释或Fluent API)来呈现此信息
信息给模型构建器。使用数据注释,您将使用注释
称为
两个实体之间的多重双向关系。您可以添加配置(使用数据注释或Fluent API)来呈现此信息
信息给模型构建器。使用数据注释,您将使用注释
称为
InverseProperty
.使用Fluent API,您将使用Has / With方法的组合来指定这些关系的正确结尾。
使用数据注释可能是这样的:
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")] [InverseProperty("Students")] public virtual City BirthCity { get; set; } [ForeignKey("LivingCityID")] public virtual City LivingCity { get; set; } }
通过这种方式,您明确指定要将BirthCity导航属性与“关系”另一端的“学生”导航属性相关联。
使用Fluent Api可能是这样的:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>().Hasrequired(m => m.BirthCity) .WithMany(m => m.Students).HasForeignKey(m=>m.BirthCityId); modelBuilder.Entity<Student>().Hasrequired(m => m.LivingCity) .WithMany().HasForeignKey(m=>m.LivingCityId); }
有了这个最后的解决方案,你不需要使用任何attibute。
现在,@ChristPratt的建议在每个关系的City类中都有一个学生的收藏是非常有用的。如果这样做,那么使用数据注释的配置可能是这样的:
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")] [InverseProperty("BirthCityStudents")] public virtual City BirthCity { get; set; } [ForeignKey("LivingCityID")] [InverseProperty("LivingCityStudents")] public virtual City LivingCity { get; set; } }
或使用Fluent Api遵循相同的想法:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>().Hasrequired(m => m.BirthCity) .WithMany(m => m.BirthCityStudents).HasForeignKey(m=>m.BirthCityId); modelBuilder.Entity<Student>().Hasrequired(m => m.LivingCity) .WithMany(m => m.LivingCityStudents).HasForeignKey(m=>m.LivingCityId); }
原文地址:https://www.jb51.cc/aspnet/253724.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。