Dans les versions précédentes d’Entity Framework, pour matérialiser une relation de type plusieurs à plusieurs avec l’approche Code First, il suffisait simplement de disposer dans chaque classe entité, une propriété représentant une collection d’objets de la classe entité en lien.Prenons par exemple les classes entités Categorie et Post ci-dessous :
| Code c# : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Categorie { public int Id { get; set; } public string Libelle { get; set; } public string UrlSlug { get; set; } public ICollection<Post> Posts { get; set; } } public class Post { public int Id { get; set; } public string Titre { get; set; } public string Contenu { get; set; } public DateTime DatePublication { get; set; } public TimeSpan HeurePublication { get; set; } public string UrlSlug { get; set; } public ICollection<Categorie> Categories { get; set; } } |
Cependant, si vous procédez à la génération de votre base de données en utilisant Entity Framework Core, vous obtiendrez l’erreur suivante :
Unable to determine the relationship represented by navigation property 'Categorie.Posts' of type 'ICollection<Post>'. Either manually configure the relationship, or ignore this property from the model.
| Code c# : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 | public class PostCategorie { public int PostId { get; set; } public Post Post { get; set; } public int CategorieId { get; set; } public Categorie Categorie {get; set;} } |
| Code c# : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Categorie { public int Id { get; set; } public string Libelle { get; set; } public string UrlSlug { get; set; } public ICollection<PostCategorie> PostCategories { get; set; } } public class Post { public int Id { get; set; } public string Titre { get; set; } public string Contenu { get; set; } public DateTime DatePublication { get; set; } public TimeSpan HeurePublication { get; set; } public string UrlSlug { get; set; } public ICollection<PostCategorie> PostCategories { get; set; } } |
| Code c# : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostCategrie>() .HasKey(t => new { t.PostId, t.CategorieId }); modelBuilder.Entity<PostCategrie>() .HasOne(pt => pt.Post) .WithMany(p => p.PostCategries) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostCategrie>() .HasOne(pt => pt.Categorie) .WithMany(t => t.PostCategries) .HasForeignKey(pt => pt.CategorieId); } |
Vous avez lu gratuitement 3 084 articles depuis plus d'un an.
Soutenez le club developpez.com en souscrivant un abonnement pour que nous puissions continuer à vous proposer des publications.
Soutenez le club developpez.com en souscrivant un abonnement pour que nous puissions continuer à vous proposer des publications.