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
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);
}