How to simulate a 1 to 0..1 relationship when you must have a 1 to 1

If you take the Noam edm, you have a 1 to 1 relationship that you must have because the relationship is on the PK of the two entities which are the same.

Now imagine that in his sample, FrontImage, TopImage and SideImage are nullable.

We can imagine creating a new Product without a new ProductImages.

If you do this, you will have an exception on the SaveChanges because you have a 1 to 1 relationship so you must have a ProductImages associated.

My idea is to automaticaly create the ProductImages (if it does’nt exist) on the SaveChanges.

What I suggest is to extend the ObjectContext, to use the partial method OnContextCreated to add handler to the SavingChanges event:

partial class Test4125924Entities


    partial void OnContextCreated()


        SavingChanges += (sender, e) =>


            foreach (var product in ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(ose => ose.Entity).OfType<Product>())

                if (product.ProductImages == null)

                    product.ProductImages = new ProductImages();




This entry was posted in 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *