EF'de bir test yapmayı deniyorum, çoktan fazla ilişki oluşturuyorum, çünkü her zaman Birebir veya Biri ile Çok - Eşleştirdiğimden, İnternette bir örnek alıyorum deneme için, örneğin insert kayıtları için çalıştığını amaVarlık çerçeve kodunda birçok ilişkiye eşleme ilk olarak
İşteBen sitede
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Course> CoursesAttending { get; set; }
public Person()
{
CoursesAttending = new HashSet<Course>();
}
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<Person> Students { get; set; }
public Course()
{
Students = new HashSet<Person>();
}
}
bu kodu almak, ben HashSet
olduğunu bilmiyorum, benim sınıfları olduğunu kayıtlarını okuyamaz İşte benim Bağlamım
public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }
public SchoolContext()
: base("MyDb")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.CoursesAttending).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
});
}
}
Ben kayıtlarını eklemek
sağstatic void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Course math = new Course();
Course history = new Course();
Course biology = new Course();
math.Title = "Math";
history.Title = "History";
biology.Title = "Biology";
db.Courses.Add(math);
db.Courses.Add(history);
db.Courses.Add(biology);
Person john = new Person();
john.FirstName = "John";
john.LastName = "Paul";
john.CoursesAttending.Add(history);
john.CoursesAttending.Add(biology);
db.People.Add(john);
db.SaveChanges();
}
}
Ama gösteri içerik seçme kayıt çalıştığınızda, işe değil, sadece bir şey
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Pearson p = db.Peasons.First();
Console.WriteLine(p.CoursesAttending.First().Title);
}
}
ben veritabanında kontrol ettirdik
yazdırmak olduğunu kayıtları mevcuttur, sorun nedir?
Lütfen önce kodla birçok ilişkide nasıl seçim yapacağımı öğrenin.
Çoktan çoğa ilişkisi içinde gezinme özellikleri üzerinde '.Add()' işlevini kullanırsanız, EF otomatik olarak karşılık gelen bir ortak tabloyu güncelleştirir mi? – Celdor
@Celdor EF, karşılık gelen birleştirme tablosunu güncelleştirir. – IFink