views:

1512

answers:

2

Suppose I have these tables:

Fruits
 - FruitID       INT PK
 - FruitName     NVARCHAR(30)
 - FruitStatusID INT FK: Statuses

Statuses
 - StatusID      INT PK
 - StatusName    NVARCHAR(30)

How do I update both the Fruit's name and its status in the database in these situations?:

  1. Update a piece of Fruit that came from a previous L2E call
  2. given an integer corresponding to the FruitID (that is, I don't have a full Fruit object in hand to start with)

VB or C# is fine, thanks!

+2  A: 

This works but isn't what I was hoping for:

int StatusID = 4; // Some ID
Fruit.FruidIDReference.EntityKey = 
    New EntityKey("MyEntities.Statuses", "StatusID", StatusID)

Surely there's a cleaner way to do this that doesn't require hard-coding strings (which introduces run-time exceptions if I make a typo).

Michael Haren
I just also realized: you can construct the first two parameters from the existing EntityKey value, so you don't have to hard-code them: New EntityKey(Fruit.FruitIDReference.EntityKey.EntityContainerName + "." + Fruit.FruitIDReference.EntityKey.EntitySetName, Fruit.FruitIDReference.EntityKey.EntityKeyValues[0].Key, 0)
Dave Swersky
I'll give that a try, thanks for following up
Michael Haren
A: 

If a Fruit object is passed on to another method, you can:

  1. Pass a reference to the context object along with the Fruit and call SaveChanges()

  2. Make your edits to the Fruit object in the downlevel method and call SaveChanges() in the calling method (you can check to see if it has been modified if you want to avoid unnecessary DB calls.)

Code:

//Change the name
FruitEntities fe = new FruitEntities();
Fruit f = fe.Friuts.First();
f.FruitName = "NewName";
fe.SaveChanges();

//Get a fruit by ID and change the status
//Statuses will need to be included as an Entity in your model with an association to Fruits
int Id = 2;
int newStatusID = 0;
FruitEntities fe = new FruitEntities();
Fruit f = (from x in fe.Fruits
           where x.FruitID == Id
           select x).First();
Status s = (from y in fe.Statuses
            where y.StatusID = newStatusID
            select y).First();
f.Status = s;
fe.SaveChanges();
Dave Swersky
This is nice because nothing is hard-coded in strings, but it requires a round trip to the database to load the status. Is there any way to get around that?
Michael Haren
Since the Statuses amounts to an enum that doesn't change often (if ever), you could save a copy of the Statuses collection in memory (Application state for web) and grab them as necessary.
Dave Swersky
Another tip: This is a lot of code, you might consider writing an extension method or something as a helper to keep your code tidy.
Dave Swersky