EF Code First with many to many self referencing relationship

前端 未结 1 1751
感动是毒
感动是毒 2021-02-08 17:08

I am starting out with using the EF Code First with MVC and am a bit stumped with something. I have the following db structure (Sorry but I was not allowed to post an image unf

相关标签:
1条回答
  • 2021-02-08 17:46

    The first part of the answer is that EF4 CTP5 is not correctly mapping your POCOs to the database because it's not smart enough. If you check out the database, you get:

        CREATE TABLE RelatedProducts(
            RelatedProductID uniqueidentifier NOT NULL,
            ProductID uniqueidentifier NOT NULL,
            ProductProductID uniqueidentifier NULL,
            ProductProductID1 uniqueidentifier NULL,
            ProductProductID2 uniqueidentifier NULL,
            PRIMARY KEY CLUSTERED 
            (
                RelatedProductID ASC
            )
        ) ON [PRIMARY]  
    

    Yuck! This needs to be fixed with some manual work. In your DbContext, you add rules like so:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>()
                .Property(p => p.ProductID)
                .HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);
    
            modelBuilder.Entity<RelatedProduct>()
                .HasKey(rp => new { rp.ProductID, rp.RelatedProductID });
    
            modelBuilder.Entity<Product>()
                .HasMany(p => p.RelatedProducts)
                .WithRequired(rp => rp.Product)
                .HasForeignKey(rp => rp.ProductID)
                .WillCascadeOnDelete();
    
            modelBuilder.Entity<RelatedProduct>()
                .HasRequired(rp => rp.SimilarProduct)
                .WithMany()
                .HasForeignKey(rp=> rp.RelatedProductID)
                .WillCascadeOnDelete(false);
    
            base.OnModelCreating(modelBuilder);
        }
    
    0 讨论(0)
提交回复
热议问题