Задайте вопросЗадайте вопрос
 

ОтвеченоLINQ to SQL - Update an object using a different DataContext

  • 2 января 2008 г. 13:11Yoni Mazar Медали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     

    Hi Guys,

     

    Maybe it is just me (I am used to DataSets which hold their own state...) but the whole Attached/Dettached objects in LINQ to SQL is a bit confusing. None of the examples I have read all over the net seemed to help me with this problem:

     

    Consider the Products table (Northwind).

     

    I have a DAL which is stateless. DataContexts are being recreated over and over again (For each logic opertaion...like I used to do with SQL connections)

     

    I would like to simulate the following scenario:

     

    1) GetProduct(int id)

    Create DataContext

    Query table

    Dispose DataContext

    Return result

     

    2) Modify Product (lets say that this is done in my client)

     

    3) UpdateProduct (Product prod)

    Create DataContext

    Attach the object

    Submit Changes

    Dispose DataContext

     

    This is not working... I tried dettaching the updated object, I even added a timestamp column, but still it doesnt work...

     

    How should I do it using LINQ??

     

     

     

Ответы

  • 21 января 2008 г. 16:51Matt Warren - MSFT Медали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     Отвечено

    The Attach methods are designed to be used strictly for multi-tier round-tripping where the objects you attach back are never the same instances as previously retrieved. This is a deviation from the normal pattern of usage which is to keep the DataContext alive for the entire unit of work that you are performing.

     

    Since the objects don't ferry their own changes, you have to invent a transport or API that does this and then supply the change information to the DataContext before you attempt to submit your changes back to the database.  This could be as simple as having a web method that recieves an entity plus a few additional changed values, one that recieves two distinct entities (old and new) or one that recieves only the changed entity yet has a version field that can be used instead of the original values that would otherwise be needed to perform the appropriate optimistic concurrency checks.

     

    To use LINQ to SQL correctly, you should maintain a stateful DAL, unless you are actually moving data across physical or process boundary tiers.

     

Все ответы