locked
How to Update Foreign Keys in Entity? RRS feed

  • Question

  • Hi,

    I'm new to LINQ to Entities and was looking for a sample app or webcast that shows me how to update the Foreign Keys in an Entity.

    I understand how to save the entitiy, but let's say you are creating a new Customer. One of the Foreign Keys in customer is StateID (selected using a dropdown).

    How do I stuff the StateID in the new Customer entitiy?

    Also, if you know of any MVC/LINQ to Entities sample apps that I can download, that would be a bonus!

    Thanks,

    Murph

    Monday, June 9, 2008 8:31 PM

Answers

  • After a little bit more head banging, this is what I found to work.  I'm not sure it's the best approach, but it does work. If anyone has the OPTIMAL approach, I'd be greatful!

     

    First of all you cannot update the Foreign Keys in an Entity--they are read-only. You must update the whole entity. My guess is that this approach keeps the data in the Enties in the project exactly as what's in the database--a good thing.

    So here is how you change the Employee (Salesperson) to Leverling (EmployeeID 3) for the first order for the first customer in the Northwind database:

     

    using (NorthwindEntities db = new NorthwindEntities()) {

    var custs = from c in db.Customers

    select c.;

    var firstCust = custs.First();

    firstCust.Orders.Load();

    var firstOrder = firstCust.Orders.First();

    var assignedEmp = (from emps in db.Employees where emps.EmployeeID == 3 select emps).AsEnumerable().First();

    firstOrder.Employees = assignedEmp;

    db.SaveChanges();

    }

    I hope this is helpful to someone.

    Murph

    Tuesday, June 10, 2008 8:58 PM