شما به دو طریق میتوان این کار را انجام دهید یکی از آنها از طریق Data Annotation و دیگری Fluent Api می باشد. فرض کنید یک کلاس Student داریم که دارای محل تولد و محل زندگی می باشد و محل زندگی آن توسط کلاسی به نام City مشخص می شود. به شکل زیر:
public class Student { public int BirthCityId { get; set; } public int LivingCityId { get; set; } public virtual City BirthCity { get; set; } public virtual City LivingCity { get; set; } } public class City { public virtual ICollection<Student> BirthCityStudents { get; set; } public virtual ICollection<Student> LivingCityStudents { get; set; } }
اگر میخواهید از Data Annotation استفاده کنید به شکل زیر عمل کنید:
public class Student { 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 استفاده کنید به سراغ Context خود بروید و سپس متد OnModelCreating را override کنید و رابطه های مورد نظر رو اعمال کنید:
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); }
خیلی ممنون ولی من بصورت بالا کار کردم
به خطای زیر برخوردم میشه بگید دلیل این خطا چیه؟
هیچ کاربری تا کنون از این پست تشکر نکرده است
با ما تماس بگیرید تا در این مسیر همراهتان باشیم :)