How can I update the foreign key value of an object using LINQ to Entities?

Suppose I have these tables:

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

Statuses
 - StatusID      INT PK
 - StatusName    NVARCHAR(30)

      

How to update the name and name of Fruit in the database in the following situations:

  • Update the Fruit fragment that appeared in the previous call to L2E
  • given an integer corresponding to the FruitID (that is, I don't have a complete Fruit object to start with)

VB or C # is great, thanks!

+1


source to share


2 answers


This works , but it is not what I was hoping for:

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

      



Of course there is a cleaner way to do this that doesn't require strict coding strings (which throws runtime exceptions if I make a typo).

+2


source


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

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

  • Make your changes to the Fruit object in the downlevel method and call SaveChanges () in the calling method (you can check if it has changed 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();

      

0


source







All Articles