Defining Constraints in an EF4 model that don’t exist in the database

In the first version of Entity Framework, if you wanted to create a PK/FK association between entities where there was no such constraint defined in the database you have to manually edit the SSDL (and lose that edit if you update the model from db).

Why would you want to do this? The typical use case is when you are stuck with a database that is poorly designed and you are not allowed to make changes to it.

In Entity Framework 4, as long as the Primary Keys are defined in the db (otherwise the entities are read only like views, although you can map stored procs to them and make them updatable) and you have foreign keys in the model, you can define the constraint easily.

Here’s a dependent table. It does have a foreign key property (with a typo :)) but notice under indexes there is no PK_FK defined pointing back to the table which PrimartyID(sic) refers to.

 

noconstraint

 

When I pull this table and PrimaryTable into the model there is no association between them.

I create an association:

noconstraint2

and then define the constraint in the model. You need to open the properties window of the association and then click on the Referential Constraint ellipses

noconstraint2a

to get to the ref constraint dialog:

noconstraint3

This is a new feature that comes with foreign key associations. You can’t do this if you do not include foreign key ids in your model.

Now for the test:

  private static void fakePKFK()
    {
      var context = new manytomanytestEntities();
      var list = context.PrimaryTables.Include("DependentTables").ToList();
      var firstPrimary = list[0];
      var newDependant = new DependentTable {DependentName = "ChildNew for FIrst"};
      firstPrimary.DependentTables.Add(newDependant);
      context.SaveChanges();
    }

And it works. THe query returns graphs of primary & dependents. The SaveChanges inserts a new dependent. Rerunning the code brings me back the new dependent in the primary’s collection.

Have not tested *:*. Someone has already asked me about code only. I don’t know. But feel free to take the time to test it out and let me know! 🙂

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.