4

I found something weird. Let's say I have a Car model and a Company model.

So my Car model has a CompanyId row.

Let's say I change a Car's CompanyId then I SubmitChanges on the DataContext.

Here's my problem: The CompanyId of my Car model gets updated. But the Car.Company relation does NOT.

So if I change Car.CompanyId from 1 to 2. Then I output Car.Company.CompanyId, it'll show up 1 instead of 2.

So my question is: Is there a way to update EVERYTHING in the DataContext?

I'm currently using:

public void RefreshCollection()
{
    // On rafraichit les données à partir de la DB.
    dataContext.Refresh(RefreshMode.KeepChanges);

    // On va chercher les données complête de la table.
    purchaseOrders = from po in dataContext.PurchaseOrders
                     orderby po.PurchaseOrderId ascending
                     select po;
}

To update my collection.

And:

private void sauvegarderToolStripMenuItem_Click(object sender, EventArgs e)
{
    purchaseOrder.OrderDate = orderDate.Value;
    purchaseOrder.RequiredDate = requiredDate.Value;
    purchaseOrder.ShipTo = shipTo.Text;
    purchaseOrder.State = helper.ConvertComboBoxIndexToStateIndex(
        stateKey.SelectedIndex);

    // On cast un autre type pour le forcer à être un ComboBoxItem
    var supplierItem = (ComboBoxItem)supplierId.SelectedItem;
    purchaseOrder.SupplierId = supplierItem.Id;

    dataContext.SubmitChanges();
}

To submit my changes.

casperOne
  • 73,706
  • 19
  • 184
  • 253
Tommy B.
  • 3,591
  • 14
  • 61
  • 105
  • 1
    perhaps if you post some of the code we will be able to help – Kris Ivanov Jan 27 '11 at 15:56
  • I can't see what code I should post. The problem isn't directly in the code since this is pretty simple code. I just want to know if that ever happened to someone else and if so then how to fix it. – Tommy B. Jan 27 '11 at 16:06
  • 1
    I met the code when you perform SubmitChanges, do you get knew context? are the entities attached? etc. – Kris Ivanov Jan 27 '11 at 16:08
  • I added the code with the SubmitChanges. The PurchaseOrder entity is related to the Supplier entity. If that's what you meant. Thanks :) – Tommy B. Jan 27 '11 at 16:10
  • 1
    http://stackoverflow.com/questions/479791/setting-foreign-keys-in-linq-to-sql – Adam Robinson Feb 08 '11 at 18:11
  • @Adam Robinson: Ironically, that's the closest answer I received yet. Post this as an answer and I'll give you 50 points ;) Thanks! – Tommy B. Feb 08 '11 at 20:39

5 Answers5

2

I think your line

  purchaseOrder.SupplierId = supplierItem.Id;

should read more like

  purchaseOrder.Supplier = supplierItem;

Just guessing the properties.

You also might want to call dataContext.Refresh() on the purchaseOrder after the SaveChanges()

H H
  • 263,252
  • 30
  • 330
  • 514
  • Thanks for your answer, I think it's a step towards the good way but I get a foreign key error: An attempt was made to remove a relationship between a PurchaseOrder and a Supplier. However, one of the relationship's foreign keys (Supplier.SupplierId) cannot be set to null. :\ Any ideas? – Tommy B. Jan 27 '11 at 18:05
  • It depends on how you got purchaseOrder, looks like filling in a new one but how was it created? Also supplierItem should be tracked by the same context etc. – H H Jan 27 '11 at 18:13
  • purchaseOrder was loaded from a LINQ query, the supplier as well. PurchaseOrder was linked to another Supplier, I changed it, and now I get the FK error. The same context is used for both of the transactions. Thanks :) – Tommy B. Jan 27 '11 at 18:27
1

Just changing the ID is not enough to also change the associated Company object. You need to load the Company object you want and assign it to Car.Company. This will also update the Car.CompanyID property.

Something like:

var car = context.Cars.First(); // pick your car
var newCompany = context.Companies.First(); // pick your company
car.Company = newCompany;
context.SubmitChanges();
Alex J
  • 9,905
  • 6
  • 36
  • 46
1

Not sure if it is a viable option here, but you always have the option of taking your query, including the related entities you desire, and attach it, like so:

purchaseOrders = from po in dataContext.PurchaseOrders.Include("Company")
                     orderby po.PurchaseOrderId ascending
                     select po;

dataContext.Attach(purchaseOrders);
Benny
  • 3,899
  • 8
  • 46
  • 81
1

You may want to check out the answers to this question.

Community
  • 1
  • 1
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
0

Try to open a separate DataContext on every operation. Ideally, any update operation should end with SubmitChanges AND closing of the DataContext. DataContext is a lightweight object and should not add much overhead in that scenario. For example:

public void RefreshCollection()
{
    using (var dataContext = CreateDataContext())
    {
        // On va chercher les données complête de la table.
        purchaseOrders = from po in dataContext.PurchaseOrders
                         orderby po.PurchaseOrderId ascending
                         select po;
    }
}

private void sauvegarderToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (var dataContext = CreateDataContext())
    {
        purchaseOrder.OrderDate = orderDate.Value;
        purchaseOrder.RequiredDate = requiredDate.Value;
        purchaseOrder.ShipTo = shipTo.Text;
        purchaseOrder.State = helper.ConvertComboBoxIndexToStateIndex(
            stateKey.SelectedIndex);

        // On cast un autre type pour le forcer à être un ComboBoxItem
        var supplierItem = (ComboBoxItem)supplierId.SelectedItem;
        purchaseOrder.SupplierId = supplierItem.Id;

        dataContext.SubmitChanges();
    } 
}
SlavaGu
  • 817
  • 1
  • 8
  • 15
  • 1
    -1. While it's true that a data context's lifetime should be as short as possible, simply saying that you should create a new one for every operation is much too simplistic. The context must exist as long as change tracking for the entity is to take place. – Adam Robinson Feb 08 '11 at 18:10